How do I break out of nested loops in Java?

前端 未结 30 2764
梦毁少年i
梦毁少年i 2020-11-21 11:51

I\'ve got a nested loop construct like this:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do somethin         


        
30条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 11:59

    Labeled break concept is used to break out nested loops in java, by using labeled break you can break nesting of loops at any position. Example 1:

    loop1:
     for(int i= 0; i<6; i++){
        for(int j=0; j<5; j++){
              if(i==3)
                break loop1;
            }
        }
    

    suppose there are 3 loops and you want to terminate the loop3: Example 2:

    loop3: 
    for(int i= 0; i<6; i++){
    loop2:
      for(int k= 0; k<6; k++){
    loop1:
        for(int j=0; j<5; j++){
              if(i==3)
                break loop3;
            }
        }
    }
    

提交回复
热议问题