关于break和continue,众所周知,break是跳出当前循环,continue是跳出本次循环。
但是在多重循环中,我们可能会模糊概念:break是跳出全部循环还是只是某层循环?–>跳出的是break所在层的循环即当前循环。
结论:只要记住,break和continue只对当层循环有用,对外层循环没有影响。
跳出单层循环:
例:
public static void main (String args[]) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j == 2) break;
System.out.println("i = " + i + "; j = " + j);
}
}
System.out.println("==============");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j == 2) continue;
System.out.println("i = " + i + "; j = " + j);
}
}
}
结果:
i = 0; j = 0
i = 0; j = 1
i = 1; j = 0
i = 1; j = 1
i = 2; j = 0
i = 2; j = 1
i = 3; j = 0
i = 3; j = 1
==============
i = 0; j = 0
i = 0; j = 1
i = 0; j = 3
i = 1; j = 0
i = 1; j = 1
i = 1; j = 3
i = 2; j = 0
i = 2; j = 1
i = 2; j = 3
i = 3; j = 0
i = 3; j = 1
i = 3; j = 3
如何直接跳出多层循环:
可以在外层循环前面定义一个标号,然后在内层循环中使用带有标号break或者continue的语句,就可以直接跳出多重循环。
例:
public static void main (String args[]) {
grade1:
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j == 2) break grade1;
System.out.println("i = " + i + "; j = " + j);
}
}
System.out.println("==============");
grade2:
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j == 2) continue grade2;
System.out.println("i = " + i + "; j = " + j);
}
}
}
结果:continue的效果有点和之前的break类似,意思是继续从grade2开始。
i = 0; j = 0
i = 0; j = 1
==============
i = 0; j = 0
i = 0; j = 1
i = 1; j = 0
i = 1; j = 1
i = 2; j = 0
i = 2; j = 1
i = 3; j = 0
i = 3; j = 1