Java Reference
In-Depth Information
PITFALL: (continued)
This sort of problem is common when loops are terminated by checking a numeric
quantity using == or != . When dealing with numbers, it is always safer to test for pass-
ing a value. For example, the following will work fi ne as the fi rst line of our while loop:
while (number < 12)
With this change, number can be initialized to any number and the loop will still
terminate.
There is one subtlety about infi nite loops that you need to keep in mind. A loop
might terminate for some input values but be an infi nite loop for other values. Just
because you tested your loop for some program input values and found that the loop
ended does not mean that it will not be an infi nite loop for some other input values.
A program that is in an infi nite loop might run forever unless some external force
stops it, so it is a good idea to learn how to force a program to terminate. The method
for forcing a program to stop varies from operating system to operating system. The
keystrokes Control-C will terminate a program on many operating systems. (To type
Control-C, hold down the Control key while pressing the C key.)
In simple programs, an infi nite loop is almost always an error. However, some pro-
grams are intentionally written to run forever, such as the main outer loop in an airline
reservation program that just keeps asking for more reservations until you shut down
the computer (or otherwise terminate the program in an atypical way).
Nested Loops
It is perfectly legal to nest one loop statement inside another loop statement. For
example, the following nests one for loop inside another for loop:
nested loops
int rowNum, columnNum;
for (rowNum = 1; rowNum <= 3; rowNum++)
{
for (columnNum = 1; columnNum <= 2; columnNum++)
System.out.print(" row " + rowNum + " column " + columnNum);
System.out.println( );
}
VideoNote
Nested Loop
Example
This produces the following output:
row 1 column 1 row 1 column 2
row 2 column 1 row 2 column 2
row 3 column 1 row 3 column 2
For each iteration of the outer loop, the inner loop is iterated from beginning to end
and then one println statement is executed to end the line.
(It is best to avoid nested loops by placing the inner loop inside a method definition
and placing a method invocation inside the outer loop. Method definitions are covered
in Chapters 4 and 5 .)
 
Search WWH ::




Custom Search