DEV Community

Cover image for Java 的迴圈控制
Leon
Leon

Posted on • Originally published at editor.leonh.space

Java 的迴圈控制

Break

break 用來中斷整個迴圈:

for (int i = 0, i < 10, i++) {
    if (i = 2) {
        break; // i = 2 就中斷整個迴圈
    } else {
        System.out.println(i);
    }
}
Enter fullscreen mode Exit fullscreen mode

輸出:

0
1
Enter fullscreen mode Exit fullscreen mode

Continue

continue 用來略過某次迴圈:

for (int i = 0, i < 5, i++) {
    if (i = 2) {
        continue; // 跳過 i = 2 的迴圈
    } else {
        System.out.println(i);
    }
}
Enter fullscreen mode Exit fullscreen mode

輸出:

0
1
3
4
Enter fullscreen mode Exit fullscreen mode

Label

如果是巢狀迴圈的話勒?

Java 的迴圈是可以命名的,稱為 label,可以指定要 breakcontinue 的是哪一層的迴圈:

labelA: while (i > 0) {
    labelB: while (j > 0) {
        if (j = 2) {
            break labelA; // 會中斷整個 labelA
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

帥吧!

Top comments (0)