Java中跳出多重嵌套循环的方法

一、使用标号

1、多重嵌套循环前定义一个标号

2、里层循环的代码中使用带有标号 break 的语句

 1     public static void main(String[] args) {
 2         ok:
 3         for(int i=0;i<15;i++){
 4             for(int j=0;j<15;j++){
 5                 System.out.println("i:"+i+",j:"+j);
 6                 if(j==3){
 7                     break ok;
 8                 }
 9             }
10         }
11     }
跳出多重嵌套循环(方法一)

二、外层循环条件被内层循环修改 

 1     public static void main(String[] args) {
 2         for(int i=0;i<15;i++){
 3             for(int j=0;j<15;j++){
 4                 System.out.println("i:"+i+",j:"+j);
 5                 if(j==3){
 6                     i=16;
 7                     break;
 8                 }
 9             }
10         }
11     }
跳转多重嵌套循环(方法二)

三、抛出异常

 1     public static void main(String[] args) {
 2         try{
 3             for(int i=0;i<5;i++){
 4                 for(int j=0;j<5;j++){
 5                     System.out.println("i:"+i+",j:"+j);
 6                     if( j==3 ){
 7                         throw new Exception();
 8                     }
 9                 }
10             }
11         } catch (Exception e){
12             System.out.println("抛出异常,跳转多重嵌套循环体");
13         }
14     }
跳出多重嵌套循环(方法三)

猜你喜欢

转载自www.cnblogs.com/debjJava/p/12038133.html