笔试题 在 Java 中,如何跳出当前的多重嵌套循环?

public class Demo {
public static void main(String[] args) {
System.out.println("方法一:标号方式");
outerloop:
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break outerloop;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done"); System.out.println("方法二:条件控制");
boolean finished = false;
for (int i = 1; i < 5 && !finished; i++) {
for (int j = 1; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
finished = true;
break;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done"); System.out.println("方法二变形:条件控制");
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
i = 5;
break;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done"); System.out.println("方法三:抛出异常");
try {
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
throw new Exception();
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");// 此行代码不会执行
} catch (Exception e) {
// System.out.println("e");
}
}
}

参考答案

```
方法一:标号方式
1 1
1 2
1 3
1 4
2 1
2 2
2 3
Breaking
Done
方法二:条件控制
1 1
1 2
1 3
1 4
2 1
2 2
2 3
Breaking
Done
方法二变形:条件控制
1 1
1 2
1 3
1 4
2 1
2 2
2 3
Breaking
Done
方法三:抛出异常
1 1
1 2
1 3
1 4
2 1
2 2
2 3
Breaking
```

方法一:标号方式

System.out.println("方法一:标号方式");
outerloop:
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break outerloop;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");

参考答案

```
方法一:标号方式
1 1
1 2
1 3
1 4
2 1
2 2
2 3
Breaking
Done
```

方法二:条件控制

System.out.println("方法二:条件控制");
boolean finished = false;
for (int i = 1; i < 5 && !finished; i++) {
for (int j = 1; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
finished = true;
break;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");

参考答案

```
方法二:条件控制
1 1
1 2
1 3
1 4
2 1
2 2
2 3
Breaking
Done
```
System.out.println("方法二变形:条件控制");
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
i = 5;
break;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");

参考答案

```
方法二变形:条件控制
1 1
1 2
1 3
1 4
2 1
2 2
2 3
Breaking
Done
```

方法三:抛出异常

System.out.println("方法三:抛出异常");
try {
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
throw new Exception();
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");// 此行代码不会执行
} catch (Exception e) {
// System.out.println("e");
}

参考答案

```
方法三:抛出异常
1 1
1 2
1 3
1 4
2 1
2 2
2 3
Breaking
```

参考资料

04-30 20:28