(^238) | File Objects and Looping Statements
Let’s look at another example. For nested count-controlled loops, the pattern looks like
this (where outCountis the counter for the outer loop,inCountis the counter for the inner loop,
and limit1and limit2are the number of times each loop should be executed):
outCount = 1; // Initialize outer loop counter
while(outCount <= limit1)
{
inCount = 1; // Initialize inner loop counter
while(inCount <= limit2)
{
inCount++; // Increment inner loop counter
}
outCount++; // Increment outer loop counter
}
Here, both the inner and outer loops are count-controlled loops, but the pattern can be
used with any combination of loops. The following code fragment shows a count-controlled
loop nested within an EOF-controlled loop. The outer loop inputs an integer value telling how
many asterisks to print on each line of an output file. (We use the numbers to the right of the
code to trace the execution of the code.)
line = dataFile.readLine(); 1
while(line != null) 2
{
starCount = Integer.parseInt(line); 3
loopCount = 1; 4
while(loopCount <= starCount) 5
{
outFile.print('*'); 6
loopCount++; 7
}
outFile.println(); 8
line = dataFile.readLine(); 9
}
outFile.println("End"); 10
To see how this code works, let’s trace its execution with these data values (
end-of-file):
3
1
やまだぃちぅ
(やまだぃちぅ)
#1