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

(singke) #1
ptg7068951

Naming a Loop 101

In this loop, the statements are handled normally unless the value of index
equals 400. In that case, the continuestatement causes the loop to go
back to the whilestatement instead of proceeding normally to the
System.out.println()statement. Because of the continuestatement,
the loop never displays the following text:


The index is 400


You can use the breakand continuestatements with all three kinds of loops.


The break statement makes it possible to create a loop in your program
that’s designed to run forever, as in this example:


while(true) {
if (quitKeyPressed == true) {
break;
}
}


Naming a Loop


Likeother statements in Java programs, you can place loops inside each
other. The following shows a forloop inside a whileloop:


int points = 0;
int target = 100;
while(target <= 100) {
for(int i = 0; i < target; i++) {
if (points > 50)
break;
points = points + i;
}
}


In this example, the breakstatement causes the forloop to end if the
pointsvariable is greater than 50. However, the whileloop never ends
because targetis never greater than 100.


In some cases, you might want to breakout of both loops. To make this
possible, you have to give the outer loop—in this example, the whilestate-
ment—a name. To name a loop, put the name on the line before the begin-
ning of the loop and follow it with a colon (:).


When the loop has a name, use the name after the breakor continuestate-
ment to indicate the loop to which the breakor continuestatement
applies. The following example repeats the previous one with the excep-
tion of one thing: If the pointsvariable is greater than 50, both loops end.

Free download pdf