Java中,break语句相信大伙都会非常熟悉,它的作用就是终结循环,但是普通的不带标签的break语句只能终结最内层的循环。
如果希望能在嵌套非常深的循环中,直接跳出最外层循环,那么就需要用到带标签的break语句。
代码能说明一切,请看示例:
------------------------------------------
FIRST_LOOP: for (int i = 0; i < 2; i++) {
SECOND_LOOP: for (int j = 0; j < 2; j++) {
THIRD_LOOP: for (int k = 0; k < 2; k++) {
FORTH_LOOP: for (int l = 0; l < 2; l++) {
System.out.println("count" + count + ": i = " + i + ", j = " + j + ", k = " + k + ", l = " + l);
count++;
if (i == 1 && l == 0) {
break FIRST_LOOP;
}
}
}
}
}
------------------------------------------
很显然,这是一个四层的嵌套循环,那么要想在满足指定条件直接结束整个循环,则必须使用带标签的break语句。
上述代码将打印出如下结果:
count0: i = 0, j = 0, k = 0, l = 0
count1: i = 0, j = 0, k = 0, l = 1
count2: i = 0, j = 0, k = 1, l = 0
count3: i = 0, j = 0, k = 1, l = 1
count4: i = 0, j = 1, k = 0, l = 0
count5: i = 0, j = 1, k = 0, l = 1
count6: i = 0, j = 1, k = 1, l = 0
count7: i = 0, j = 1, k = 1, l = 1
count8: i = 1, j = 0, k = 0, l = 0
从结果可以看出,当i == 1 && l == 0的条件满足后,循环就已经结束了,break语句成功跳到了最外层循环即FIRST_LOOP循环,并终结了FIRST_LOOP循环。
当然除了终结FIRST_LOOP循环外,break语句也可以终结SECOND_LOOP循环或者THIRD_LOOP循环,就看所要实现的逻辑了。
总结:带标签的break语句的最佳实践就是终结多层嵌套循环。
网友评论