1. 程式人生 > >java循環

java循環

spa con 用兩個 per class number span 有用 執行

Java標記For循環

我們可以讓每個for循環的名稱。 為此,在for循環之前使用標簽。它是有用的,如果在嵌套for循環中,可以使用break/continue指定循環。

通常,breakcontinue關鍵字斷開/繼續最內循環。

語法:

public class LabeledForExample  {
    public static void main(String[] args) {
        aa: for (int i = 1; i <= 3; i++) {
            bb: for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    break aa;
                }
                System.out.println(i + " " + j);
            }
        }
    }
}


執行上面的代碼,得到如下結果 -
1 1
1 2
1 3
2 1

如果使用break bb;它將打斷內循環,這是任何循環的默認行為。

public class LabeledForExample {
    public static void main(String[] args) {
        aa: for (int i = 1; i <= 3; i++) {
            bb: for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    break bb;
                }
                System.out.println(i + " " + j);
            }
        }
    }
}


執行上面的代碼,得到如下結果 -
1 1
1 2
1 3
2 1
3 1
3 2
3 3

Java無限循環

for循環中,如果使用兩個分號;,則它對於循環將是不定式的

語法:

for(;;){  
    //code to be executed  
}

示例:

public class ForExample {
    public static void main(String[] args) {
        for (;;) {
            System.out.println("infinitive loop");
        }
    }
}

執行上面的代碼,得到如下結果
nfinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c

提示: 在執行上面的程序時,您需要按ctrl + c退出程序。

java循環