Java_跳出多重嵌套循环的4种方式
Method1:定义标号
package breakFor;
public class Test1 {
public static void main(String[] args) {
test:
for(int i=0;i<10;i++) {
for(int j=0;j<10;j++) {
System.out.print(j);
if(j==5) {
break test;
}
}
}
System.out.println("跳出来了");
}
}
结果:
这种方法其实和goto异曲同工了,所以不推荐,很容易混乱。
Method2:定义Boolean类型标记
package breakFor;
public class Test2 {
public static void main(String[] args) {
boolean flag=true;
for(int i=0;i<10&&flag;i++) {
for(int j=0;j<10;j++) {
System.out.println(j);
if(j==5) {
flag=false;
break;
}
}
}
System.out.println("end");
}
}
Method 3:跳转索引:
package breakFor;
public class Test3 {
public static void main(String[] args) {
for(int i=0;i<10;i++) {
for(int j=0;j<10;j++) {
System.out.println(j);
if(j==5) {
i=10;
break;
}
}
}
System.out.println("end");
}
}
Method4:异常处理
package breakFor;
public class Test4 {
public static void main(String[] args) {
try {
for(int i=0;i<10;i++) {
for(int j=0;j<10;j++) {
System.out.println(j);
if(j==5) {
throw new Exception();
}
}
}
}catch(Exception e) {
System.out.println("end");
}
}
}
还没有评论,来说两句吧...