Java Reference
In-Depth Information
ctr = ctr + 1;
System.out.print(",");
}
System.out.print(" Indians");
System.out.println("");
}
In this case, the while loop is referred to as the outer loop and the for loop is called the inner loop.
11.
Save and run LoopTestApp.
The results will be the following:
1 little, 2 little, 3 little, Indians
4 little, 5 little, 6 little, Indians
7 little, 8 little, 9 little, Indians
10 little, 11 little, 12 little, Indians
Close, but no cigar.
We need to break out of the inner loop before the third comma on each line is printed. In addition, we want to
break out of the inner loop when the counter reaches 10. To do this we need to set up a compound if statement that
checks for the inner counter (i) value of 3 and the outer counter (ctr) value of 10. When either of these conditions is
true, a break should be performed.
12.
Add the following if condition after ctr is incremented but before the print of the comma:
if (ctr > 10 || i == 3){
break ;
}
13.
Save and run LoopTestApp.
The results will be the following:
1 little, 2 little, 3 little Indians
4 little, 5 little, 6 little Indians
7 little, 8 little, 9 little Indians
10 little Indians
Not bad. The first three lines are good, but the last line should say “Indian boys” not “Indians.” So, we will insert
an outer loop break when ctr is greater than 10. We will also add a print statement outside the outer loop to display
“Indian boys” as the last line.
14.
Add the following if condition before the print “Indians” statement in the outer loop:
if (ctr > 10){
break ;
}
15.
Save and run LoopTestApp.
Search WWH ::




Custom Search