之前写多重循环时,想跳出到最外层时,我们都知道,这个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
原文地址:https://www.cnblogs.com/dpcn/p/12053781.html
时间: 2024-10-24 23:02:15