Java Reference
In-Depth Information
FIGURE 3.8
The syntax of the continue statement
When using a label, a colon is required.
optional_label : for ( initialization ; booleanexpression ; update_statement ) {
//anywhere within the loop:
continue optional_label ;
}
When the continue statement
executes, control immediately
jumps to the update_statement .
Here's a simple for loop with an unlabeled continue statement. See if you can determine
its output:
3. for(char c = 'm'; c <= 'p'; c++) {
4. if(c == 'n') {
5. continue;
6. }
7. System.out.print(c);
8. }
The sequence of events for this loop follows:
1. c is initialized to 'm' , which is less than 'p' , so the loop body executes.
2. Line 4 is false and 'm' displays on line 7. The loop body is done, so control jumps to
the update statement and c is incremented to 'n' .
3. The loop body executes again, but this time line 4 is true so the continue executes on
line 5, causing control to jump immediately to the update statement c++ . No output
displays because line 7 is skipped.
4. The loop body executes two more times with c equal to 'o' and c equal to 'p' .
Therefore, the output is
mop
Let's look at an example with a nested loop. Study the following code and see if you can
determine what the output is:
10. for(int a = 1; a <= 4; a++) {
11. for(char x = 'a'; x <= 'c'; x++) {
12. if(a == 2 || x == 'b')
13. continue;
14. System.out.print(“ “ + a + x);
15. }
16. }
Search WWH ::




Custom Search