Breaking nested loop and main loop [duplicate]

帅比萌擦擦* 提交于 2019-12-19 16:57:59

问题


I have the following code:

int x = 100; //Or some other value

while(x > 0) {

    for(int i = 5; i > 0; i++) {

        x = x-2;

        if(x == 0)
            break;

        }

}

However, this will only break the for loop. How can I have it so that it breaks both the for and the while loops?

Cheers!


回答1:


You can use a labeled break, which redirects the execution to after the block marked by the label:

OUTER:
while(x > 0) {
    for(int i = 5; i > 0; i++) {
        x = x-2;
        if(x == 0)
            break OUTER;
    }
}

Although in that specific case, a simple break would work because if x == 0 the while will exit too.




回答2:


bool done=false;
while(!done && x > 0) {
    for(int i = 5;!done &&  i > 0 ; i++) {
        x = x-2;
        if(x == 0){
            done=true;
            break ;
        }
    }
}



回答3:


See this example

Outer:
    for(int intOuter=0; intOuter < intArray.length ; intOuter++)
    {
      Inner:
      for(int intInner=0; intInner < intArray[intOuter].length; intInner++)
      {
        if(intArray[intOuter][intInner] == 30)
        {
          blnFound = true;
          break Outer;
        }  

      }
    }



回答4:


Try to avoid breaks, there's always an other way to write your loop so you don't need it which is much 'prettier' and easier to understand if someone else has to modify your code. In your example the while loop is unnecessary but to show you how it's possible:

while(x > 0) {

  for(int i = 5; i > 0 && x!=0; i++) {

    x = x-2;

  }

}

If x equals 0, the for-loop will be left. Then your while condition will be verified: x is smaller then 0 (it's zero) so your while loop will stop executing too.



来源:https://stackoverflow.com/questions/15525727/breaking-nested-loop-and-main-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!