5.2 Looping | 237
commaCount = 0; // Initialize event counter
index = 0; // Initialize loop control count
while(index < inLine.length()) // Inner loop test
{
if (inLine.charAt(index) == ',')
commaCount++; // Update inner event count
index++; // Update inner exit condition
}
System.out.println("Found "+ commaCount + " commas on line "+ lineCount);
inLine = inFile.readLine(); // Update outer exit condition
}
System.out.println("There are "+ lineCount " lines in the file.");
The outer loop is EOF-controlled, and its process is to count input lines and run the in-
ner loop. The inner loop is count-controlled, and its process is to count the commas that it
finds on a line. Note the unusual starting and ending values for this inner count-controlled
loop. We usually begin at 1, and our ending condition is <=the maximum value. However, the
positions in a Stringare numbered starting at 0 and go up to length() – 1. In this case, be-
cause the iteration counter is also used as the position number within the string, it is more
natural to start at 0.
General Pattern
Let’s examine the general pattern of a simple nested loop. Here the dots represent places
where the processing and updating may take place in the outer loop:
...
Initialize outer loop
while( Outer loop condition )
{
...
Initialize inner loop
while( Inner loop condition )
{
Inner loop processing and update
}
}
Notice that each loop has its own initialization, test, and update steps. An outer loop could
potentially do no processing other than to execute the inner loop repeatedly. On the other
hand, the inner loop might be just a small part of the processing done by the outer loop; many
statements could precede or follow the inner loop.