java循环

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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退出程序。
















以上是关于java循环的主要内容,如果未能解决你的问题,请参考以下文章

使用从循环内的代码片段中提取的函数避免代码冗余/计算开销

java 循环变量

AVKit – 视频片段仅循环 2 次

如何使用事件侦听器来加载动画片段的循环

Java错题

c_cpp 这个简单的代码片段显示了如何使用有符号整数在C中完成插值。 for()循环确定要插入的范围