zoukankan      html  css  js  c++  java
  • 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     }
    跳出多重嵌套循环(方法三)
  • 相关阅读:
    高一下期末考试划水记
    BZOJ 1053
    积性函数与狄利克雷卷积(未完待更)
    Contest Hunter 3101
    POJ2689
    3.17爆零赛
    全概率公式
    矩阵快速幂
    模板练习
    _rqy's Code Style for OI
  • 原文地址:https://www.cnblogs.com/debjJava/p/12038133.html
Copyright © 2011-2022 走看看