java循环

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退出程序。

posted on 2017-10-08 21:51  念與北詩丶  阅读(134)  评论(0)    收藏  举报

导航