Break statement inside two while loops

后端 未结 11 1167
时光取名叫无心
时光取名叫无心 2020-12-24 14:00

Let\'s say I have this:

while(a){

  while(b){

   if(b == 10)
     break;
 }
}

Question: Will the break statement take m

相关标签:
11条回答
  • 2020-12-24 14:37

    Only from the inner one. Use labeled break if you wish to break to specific loop

    label1:
    for(){
      label2:
      for(){
          if(condition1)
          break label1;//break outerloop
    
          if(condition2)
          break label2;//break innerloop
      }
    }
    

    Also See

    • labeled break
    0 讨论(0)
  • 2020-12-24 14:39

    Only the inner loop of course.

    0 讨论(0)
  • 2020-12-24 14:40
    while (a) {
    
       while (b) {
    
          if (b == 10) {
              break;
          }
       }
    }
    

    In the above code you will break the inner most loop where (ie. immediate loop) where break is used.

    You can break both the loops at once using the break with label

    label1: 
    while (a) {
    
       while (b) {
    
          if (b == 10) {
              break label1;
          }
       }
    }
    
    0 讨论(0)
  • 2020-12-24 14:41

    The java break statement won't take you out of multiple nested loops.

    0 讨论(0)
  • 2020-12-24 14:48

    As a curious note, in PHP the break statement accept a numeric parameter which tells how many outer loops you want to break, like this:

    $i = 0;
    while (++$i) {
       switch ($i) {
          case 5:
             echo "At 5<br />\n";
             break 1;  /* Exit only the switch. */
          case 10:
             echo "At 10; quitting<br />\n";
             break 2;  /* Exit the switch and the while. */
          default:
             break;
      }
    }
    
    0 讨论(0)
  • 2020-12-24 14:49

    It will break only the most immediate while loop. Using a label you can break out of both loops: take a look at this example taken from here


    public class Test {
      public static void main(String[] args) {
        outerloop:
        for (int i=0; i < 5; i++) {
          for (int j=0; j < 5; j++) {
            if (i * j > 6) {
              System.out.println("Breaking");
              break outerloop;
            }
            System.out.println(i + " " + j);
          }
        }
        System.out.println("Done");
      }
    }
    
    0 讨论(0)
提交回复
热议问题