You need to understand the difference between labeled and unlabeled break and continue. The labeled varieties are needed only in situations where you have a nested loop, and need to indicate which of the nested loops you want to break from, or from which of the nested loops you want to continue with the next iteration. A break statement will exit out of the labeled loop, as opposed to the innermost loop, if the break keyword is combined with a label. An example of what a label looks like is in the following code:
foo:
for (int x = 3; x < 20; x++) {
while(y > 7) {
y--;
}
}
The label must adhere to the rules for a valid variable name and should adhere to the Java naming convention. The syntax for the use of a label name in conjunction with a break statement is the break keyword, then the label name, followed by a semicolon. A more complete example of the use of a labeled break statement is as follows:
boolean is True = true;
outer:
for(int i=0; i<5; i++) {
while (isTrue) {
System.out.println("Hello");
break outer;
} // end of inner while loop
System.out.println("Outer loop."); // Won't print
} // end of outer for loop
System.out.println("Good-Bye");
Running this code produces
Hello
Good-Bye
In this example the word Hello will be printed one time. Then, the labeled break statement will be executed, and the flow will exit out of the loop labeled outer. The next line of code will then print out Good-Bye. Let's see what will happen if the continue statement is used instead of the break statement. The following code example is similar to the preceding one, with the exception of substituting continue for break:
outer:
for (int i=0; i<5; 1++) {
for (int j=0; j<5; j++) {
System.out.println("Hello");
continue outer;
} // end of inner loop
System.out.println("outer"); // Never prints
}
System.out.println("Good-Bye");
Running this code produces
Hello
Hello
Hello
Hello
Hello
Good-Bye
In this example, Hello will be printed five times. After the continue statement is executed, the flow continues with the next iteration of the loop identified with the label. Finally, when the condition in the outer loop evaluates to false, this loop will finish and Good-Bye will be printed.
Given:
1. public class Breaker{
2. static String o = "";
3. public static void main(String[] args){
4. z:
5. o = o + 2;
6. for(int x=3; x<8; x++){
7. if(x == 4) break;
8. if(x == 6) break z;
9. o = o + x;
10. }
11. System.out.println(o);
12. }
13. }
What is the result?
A. 23
B. 234
C. 235
D. 2345
E. 2357
F. 23457
G. Compilation fails.
沒有留言:
張貼留言