Naming a Loop

Like other statements in Java programs, loops can be put inside of each other. The following shows a for loop inside a while loop:

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 break statement will cause the for loop to end if the points variable is greater than 50. However, the while loop will never end, because target is never greater than 100. In this case (and others), you might want to break out of both loops. To make this possible, you have to give the outer loop—in this example, the while statement—a name. To name a loop, put the name on the line before the beginning of the loop and follow it with a colon (:). Once the loop has a name, you can use the name after the break or continue statement to indicate to which loop the break or continue statement applies. Although the name of the loop is followed by a colon at the spot where the loop begins, the colon is not used with the name in a break or continue statement. The following example repeats the previous one with the exception of one thing: If the points variable is greater than 50, both loops are ended.

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


Complex for Loops

Most for loops are directly comparable to the ones used up to this point in the hour. They can also be a little more complex if you want to work with more than one variable in the for statement. Each section of a for loop is set off from the other sections with a semicolon (;). A for loop can have more than one variable set up during the initialization section, and more than one statement in the change section, as in the following:

int i, j;
for (i = 0, j = 0; i * j < 1000; i++, j += 2) {
 System.out.println(i + " * " + j + " = " + i * j);
}


These multiple statement sections of the for loop are set off by commas, as in i = 0, j = 0. This loop will display a list of equations where the i variable is multiplied by the j variable. The i variable increases by one, and the j variable increases by two during each trip through the loop. Once i multiplied by j is no longer less than 1,000, the loop will end. s of a for loop can also be empty. An example of this would be if the counter variable has already been created with an initial value in another part of the program, as in the following:

for ( ; displayCount < endValue; displayCount++) {
 // loop statements would be here
}


      
Comments