Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

do-whileLoops 99

int limit = 5;
int count = 1;
while(count < limit) {
System.out.println(“Pork is not a verb”);
count++;
}


Awhileloop uses one or more variables set up before the loop statement.
In this example, two integer variables are created: limit, which has a value
of 5, and count, which has a value of 1.


The whileloop displays the text “Pork is not a verb” four times. If you
gave the countvariable an initial value of 6 instead of 1, the text never
would be displayed.


do-while Loops


The do-whileloop is similar to the whileloop, but the conditional test
goes in a different place. The following is an example of a do-whileloop:


do {
// the statements inside the loop go here
} while(gameLives > 0);


Like the whileloop, this loop continues looping until the gameLivesvari-
able is no longer greater than 0. The do-whileloop is different because the
conditional test is conducted after the statements inside the loop, instead of
before them.


When the doloop is reached for the first time as a program runs, the state-
ments between the doand whileare handled automatically, and then the
whilecondition is tested to determine whether the loop should be repeat-
ed. If the whilecondition is true, the loop goes around one more time. If
the condition is false, the loop ends. Something must happen inside the
doand whilestatements that changes the condition tested with while, or
the loop continued indefinitely. The statements inside a do-whileloop
always are handled at least once.


The following statements cause a do-whileloop to display the same line of
text several times:


int limit = 5;
int count = 1;
do {
System.out.println(“I will not Xerox my butt”);
count++;
} while(count < limit);

Free download pdf