Like other statements in Java programs, you can place loops inside 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 causes the for
loop to end if the points
variable is greater than 50. However, the while
loop never ends because target
is never greater than 100.
In some cases, 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 (:
).
When the loop has a name, use the name after the break
or continue
statement to indicate the loop to which the break
or continue
statement applies. The following example repeats the previous one with the exception of one thing: If the points
variable is greater than 50, both loops end.
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;
}
}
When a loop’s name is used in a break
or continue
statement, the name does not include a colon.
for
LoopsA for
loop can be more complex, including more than one variable in its initialization, conditional, and change sections. 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 code:
int i, j;
for (i = 0, j = 0; i * j < 1000; i++, j += 2) {
System.out.println(i + " * " + j + " = " + (i * j));
}
In each section of the for
loop, commas are used to separate the variables as in i = 0, j = 0
. The example loop displays a list of equations where the i
and j
variables are multiplied together. The i
variable increases by one, and the j
variable increases by two during each trip through the loop. When i
multiplied by j
is equal or greater than 1,000, the loop ends.
Sections of a for
loop also can be empty. An example of this is when a loop’s counter variable already has 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
}
3.145.81.173