跳出for的多重循环有3种方式。
一、使用带有标号的的break语句
public static void main(String[] args){
int[][] array = new int[][]{{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
int target = 4;
Here:
for(int i=0;i<array.length ;i++){
System.out.println("i" + i );
for (int j = 0;j<array[0].length ;j++){
if (array[i][j]==target){
System.out.println("包含该整数");
break Here;
}
}
}
}
二、外层的循环条件收到内层的代码控制限制
public static void main(String[] args) {
int[][] array = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 4;
boolean state = true;
for (int i = 0; i < array.length && state; i++) {
System.out.println("i" + i);
for (int j = 0; j < array[0].length && state; j++) {
if (array[i][j] == target) {
System.out.println("包含该整数");
state = false;
}
}
}
}
三、使用try/catch强制跳出循环
public static void main(String[] args) {
int[][] array = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 4;
try {
for (int i = 0; i < array.length; i++) {
System.out.println("i" + i);
for (int j = 0; j < array[0].length; j++) {
if (array[i][j] == target) {
System.out.println("包含该整数");
throw new Exception();
}
}
}
} catch (Exception e) {
}
}