Java Reference
In-Depth Information
Only five lines are displayed as follows:
1 little
2 little
3 little
4 little
5 little
If you changed the break to a continue , an endless loop would be created. Why, you ask? Because the continue
occurs before the increment, ctr will never be incremented beyond 5. This means that the condition will always be
true. So, after displaying the first 4 lines, the application endlessly displays “5 little.”
This “skipping the 5th line” is a tough nut to crack!
We want to be sure that the update is always performed but that the println is not performed. So, we need to
rearrange the statements such that the increment is done first and then the println is performed. We will then put the
if statement (with the continue) before the println statement.
3.
Comment out the do while loop (don't comment out the ctr definition).
4.
Add the following do while loop:
do {
ctr = ctr + 1;
if (ctr == 5) {
continue ;
}
System.out.println(ctr + " little");
} while (ctr <= 10);
5.
Save and run LoopTestApp.
This time the results don't include the “5 little” line. However, notice that the “1 little” line does not appear at the
beginning and that there is now an “11 little” line at the end.
Because the increment is done at the beginning of the loop, the initial value of 1 is never displayed. To fix this we
will have to change the ctr initialization to 0. The “11 little” line, however, is displayed because the condition check
is performed at the end of the loop. When ctr is equal to 10, the condition is true and control passes to the top of the
loop. ctr is then incremented to 11 and the “11 little” is displayed. So, to fix this we need to change the condition to
continue processing when ctr is less than or equal to 9.
6.
Change the ctr definition from 1 to 0 and the condition from 10 to 9.
7.
Save and run LoopTestApp.
Finally, nine lines are displayed, with the 5 line being skipped.
There are occasions where you will want to nest loops (i.e., have loops within loops). For instance, we will build
an initial nested loop and then add continue and break statements to display the classic “Ten Little Indians” song.
8.
Comment out the do while loop (don't comment out the ctr definition).
9.
Change the ctr definition back to 1.
10.
Add the following nested loops:
while (ctr <= 10) {
for ( int i = 1; i <= 3; i++) {
System.out.print(" " + ctr + " little");
Search WWH ::




Custom Search