break可以跳出当前循环,continue可以跳过本次循环相信对大家并不陌生,但是如果想跳出不止一层循环呢?

看看下面的例子便清楚了,这是来自Java官方tutorial的一个小例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}

再来看看continue ,例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}

例子应该比较明白,不需要过多的解释。

但是跳过多层循环还有另外一种比较容易想到的实现方式,大家可以看看,参考一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static void main( String[] args ) {
int arr[][] = {
{1,2,3},
{4,5,6,7},
{9}
};
boolean found = false;
for(int i = 0; i < arr.length && !found; i++) {
for(int j = 0; j < arr[i].length; j++) {
System.out.println("i=" + i + ", j=" + j);
if(arr[i][j] == 5) {
found = true;
break;
}
}
}
}

各有好处,大家自行感受一下吧~~~(label标签控制有点像goto的感觉)