Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Diane Collins   on Mar 17 In Java Category.

  
Question Answered By: Fedde Bakker   on Mar 17

Loops are a section of code  that is specifically used if you want an
action to occur over and over.

Essentially there are 3 types of loops: The while loop, the do while
loop and the for loop. Each attack the same problem in different ways…

while (someBooleanValueIsTrue){
//someStuff
}

do {
//someStuff
} while (someBooleanValueIsTrue);


… Both the while loop and the do while loop are kind of the same,
however the important thing to realise is that the Boolean value is
checked at a different time. The do while loop is a "At least once"
loop, meaning it always does someStuff at least once, but the while loop
however may never fire (because the Boolean value is untrue)

(In case you don't know what I mean by Boolean value a Boolean can be
the primitive Boolean (Boolean b = true), or it can a variable
combination (someValue == someOtherValue).

The last type of loop is the for loop. I suppose the easiest way to talk
about for loops  are to show one.

for (int i = 0; i <= 9; i++){
System.out.println("HelloWorld");
}

The first thing the for loop does is set up a int value (in this case
called i, but you can call it anything), and sets its value to 0 (again
you could use anything).

It then sets its Boolean value, in this case it will loop only while i
is less than or equal to the value 9.

Then it sets count value (how much is going to be added to i every
iteration though the loop). In this case i++ just means add 1 to the value.

Then every time it has a true iteration it will print out "HelloWorld"
to the console.

All in all it can be hard to discover why you really need loops until
you get the hang of them. When you have thousands of objects that need
to be placed into data structures I know I wouldn't want to craft them
all by hand ;)

Share: 

 

This Question has 3 more answer(s). View Complete Question Thread

 


Tagged: