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

java break和continue 新技能

时间:2019-12-17 13:15:33      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:div   nbsp   false   system   color   break   ++   boolean   ==   

之前写多重循环时,想跳出到最外层时,我们都知道,这个break和continue就很“鸡肋”啊,所以,就有了这样的清新脱俗的写法:

for (int i = 0; i < 10; i++) {
    boolean breakFor = false;
    for (int j = 0; j < 10; j++) {if (j == 3) {
            breakFor = true;
            break;
        }
    }
    if (breakFor) {
        break;
    }
}
                

比较直接暴力了,每层都有个接盘侠啊这是,这要是层数多点,你要累死我咋的,

直达有一天,当我看到她的第一眼,就知道,爱了爱了

label_i:
for (int i = 0; i < 10; i++) {
    label_j:
    for (int j = 0; j < 10; j++) {
        for (int k = 0; k < 10; k++) {
            System.out.println("i = " + i + ", j = " +  j + ", k = " + k);
            if (k == 2) {
                continue label_j;
            }
            if (j == 2) {
                break label_j;
            }
            if (i == 2) {
                break label_i;
            }
        }
    }
}

如此优雅大方,输出也很直观:

i = 0, j = 0, k = 0
i = 0, j = 0, k = 1
i = 0, j = 0, k = 2
i = 0, j = 1, k = 0
i = 0, j = 1, k = 1
i = 0, j = 1, k = 2
i = 0, j = 2, k = 0
i = 1, j = 0, k = 0
i = 1, j = 0, k = 1
i = 1, j = 0, k = 2
i = 1, j = 1, k = 0
i = 1, j = 1, k = 1
i = 1, j = 1, k = 2
i = 1, j = 2, k = 0
i = 2, j = 0, k = 0

 

java break和continue 新技能

标签:div   nbsp   false   system   color   break   ++   boolean   ==   

原文地址:https://www.cnblogs.com/dpcn/p/12053781.html

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