ptg7068951
100 HOUR 8: Repeating an Action with Loops
Like a whileloop, a do-whileloop uses one or more variables that are set
up before the loop statement.
The loop displays the text “I will not Xerox my butt” four times. If you
gave the count variable an initial value of 6 instead of 1, the text would be
displayed once, even though countis never less than limit.
In a do-whileloop, the statements inside the loop are executed at least
once even if the loop condition is falsethe first time around.
Exiting a Loop
The normal way to exit a loop is for the tested condition to become false.
This is true of all three types of loops in Java. There might be times when
you want a loop to end immediately, even if the condition being tested is
still true. You can accomplish this with abreakstatement, as shown in the
following code:
int index = 0;
while(index <= 1000) {
index = index + 5;
if (index == 400) {
break;
}
}
Abreakstatement ends the loop that contains the statement.
In this example, the whileloop loops until the indexvariable is greater
than 1,000. However, a special case causes the loop to end earlier than that:
If indexequals 400, the breakstatement is executed, ending the loop
immediately.
Another special-circumstance statement you can use inside a loop is con-
tinue. The continuestatement causes the loop to exit its current trip
through the loop and start over at the first statement of the loop. Consider
the following loop:
int index = 0;
while(index <= 1000) {
index = index + 5;
if (index == 400)
continue;
System.out.println(“The index is “+ index);
}