2018年3月17日 星期六

Using Break and Continue

The break and continue keywords are used to stop either the entire loop (break) or just the current iteration (continue). Typically if you're using break or continue, you'll do an if test within the loop, and if some condition becomes true (or false depending on the program), you want to get out immediately. The difference between them is whether or not you continue with a new iteration or jump to the first statement below the loop and continue from there.

The break statement causes the program to stop execution of the innermost loop and start processing the next line of code after the block.

The continue statement causes only the current iteration of the innermost loop to cease and the next iteration of the same loop to start if the condition of the loop is met. When using a continue statement with a for loop, you need to consider the effects that continue has on the loop iteration. Examine the following code:

for (int i = 0; i < 10; i++) {
    System.out.println("Inside loop");
    continue;
}

The question is, is this an endless loop? The answer is no. When the continue statement is hit, the iteration expression still runs! It runs just as though the current iteration ended "in the natural way." So in the preceding example, i will still increment before the condition (i < 10) is checked again. Most of the time, a continue is used within an if test as follows:

for (int i = 0; i < 10; i++) {
    System.out.println("Inside loop");
    if (foo. doStuff() == 5) {
        continue;
    }
    // more loop code, that won't be reached when the above if
    // test is true
}


Given:

1. public class Breaker2{
2.     static String o = "";
3.     public static void main(String[] args){
4.         z:
5.         for(int x=2; x<7; x++){
6.             if(x == 3) continue;
7.             if(x == 5) break z;
8.             o = o + x;
9.         }
10.         System.out.println(o);
11.     }
12. }

What is the result?

A. 2
B. 24
C. 234
D. 246
E. 2346
F. Compilation fails.

沒有留言:

張貼留言