码迷,mamicode.com
首页 > 编程语言 > 详细

java循环

时间:2017-10-08 22:35:50      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:sys   代码   label   提示   ati   java   示例   print   bsp   

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循环

标签:sys   代码   label   提示   ati   java   示例   print   bsp   

原文地址:http://www.cnblogs.com/ytzl/p/7638746.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!