java break停止外层循环和continue继续外层循环

停止外层循环

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Test {
public static void main(String[] args) {
out:for (int i = 0; i < 3; i++) {
System.out.println("out:" + i);
for (int j = 0; j < 3; j++) {
if(i == 1 && j == 1) {
break out;
}
System.out.println(" in:" + j);
}
}
}
}

Click and drag to move

输出如下,可以看到(i == 1 && j == 1)条件满足后,内外层循环都停止了

1
2
3
4
5
6
out:0
in:0
in:1
in:2
out:1
in:0

Click and drag to move

继续外层循环

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Test {
public static void main(String[] args) {
out:for (int i = 0; i < 3; i++) {
System.out.println("out:" + i);
for (int j = 0; j < 3; j++) {
if(i == 1 && j == 1) {
continue out;
}
System.out.println(" in:" + j);
}
}
}
}

Click and drag to move

结果如下,可以看到(i == 1 && j == 1)条件满足后,该次的内层循环停止了,回到外层循环继续

1
2
3
4
5
6
7
8
9
10
out:0
in:0
in:1
in:2
out:1
in:0
out:2
in:0
in:1
in:2

Click and drag to move

停止多层循环

同理可以跳出或者继续多层的循环,只要在要跳出或继续的循环出设置标识即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Test {
public static void main(String[] args) {
out:for (int i = 0; i < 3; i++) {
System.out.println("out:" + i);
for (int j = 0; j < 3; j++) {
System.out.println(" in:" + j);
for (int k = 0; k < 3; k++) {
System.out.println(" inner:" + k);
if(i == 1 && j == 1 && k== 1) {
break out;
}
}
}
}
}
}

Click and drag to move

输出结果如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
out:0
in:0
inner:0
inner:1
inner:2
in:1
inner:0
inner:1
inner:2
in:2
inner:0
inner:1
inner:2
out:1
in:0
inner:0
inner:1
inner:2
in:1
inner:0
inner:1

Click and drag to move

继续多层循环类似,就不贴代码了