Java Reference
In-Depth Information
Exiting a for Loop Prematurely
Occasionally, you will want to terminate a counter-controlled or for loop
based on a different condition. For example, if the purpose of the for loop is to
look through a list for a certain item and the program finds the item before the
for loop is done, you may not want to continue the for loop. In that case, you
can force the counter to equal a number outside the range tested by the
condition. For example, if the for loop should loop through items 1 to 10 and
the program finds the item at number 3, the following code:
for (int counter=1; counter<=10; counter++)
{
//item found
counter = 11;
}
assigns the counter variable a value of 11, thus causing the condition in the
second parameter to evaluate as false and the for loop to exit.
Because the Rooms object will know exactly how many rooms there are, the
Rooms() constructor method will use a for loop and increment by 1 as it assigns
each element of the array a false state (unoccupied at the beginning).
Nested Loops
The for loop may be nested inside another for loop. Recall that nesting
means a code structure is completely enclosed within the braces or constraints of
another structure. The following code:
for (int i=1; i<=4; i++)
{
for (int j=1; j<=3; j++)
System.out.println( i + " - " + j);
}
defines a nested for loop that will produce the following 12 lines of output:
1 - 1
1 - 2
1 - 3
2 - 1
2 - 2
2 - 3
3 - 1
3 - 2
3 - 3
4 - 1
4 - 2
4 - 3
A nested loop is convenient when assigning values to two-dimensional
arrays or when keeping track of a table of numbers.
Search WWH ::




Custom Search