简体   繁体   English

不使用break语句即可脱离嵌套的for循环

[英]Break out of nested for loop without using break statement

I want to break out of a nested for loop without using the break statement. 我想脱离嵌套的for循环而不使用break语句。 The reason for this is that I get a problem later in my program when using the break statement. 原因是在稍后使用break语句时在程序中出现问题。

The source code is this: 源代码是这样的:

for (int i = 0; i < 100; i++){
    for (int j = 10; j < 100; j++) {
        code;
        if (code == true) {
            :break out here:
        }
    }
}

That's one of the few case where a goto statement wouldn' t be terrible. 那是goto语句不会很糟糕的少数情况之一。 Better yet, extract the loops into another method and use return statement, as @SR SH mentioned. 更好的是,将循环提取到另一种方法中并使用return语句,如@SR SH所述。

Try doing this, it's quite simple. 尝试这样做,这很简单。

boolean flag = true;
for (int i = 0; i < 100; i++){
    for (int j = 10; j < 100; j++) {
        code;
        if (code == true) {
            j = 101; //any value that would make the condition check in for loop false
            flag = false;
        }
     }
     if (flag==false) {
         i = 101;   //any value that would make the condition check in for loop false
     }
}

Another possibility is to use a boolean flag, that is added to the condition in the for-loops. 另一种可能性是使用布尔标志,该标志被添加到for循环的条件中。

boolean breakOut = false;
for (int i = 0; i < 100 && !breakOut; i++) {
    for (int j = 10; j < 100 && !breakOut; j++) {
        code;
        if (code == true) {
            breakOut = true;
        }
    }
}
for(int i = 0; i < 100; i++){
  for (int j = 10; j < 100; j++) {
      //code;
      if(code == true){
         j = 100; //will cancel the inner for loop.
      }
  }
}

根据要中断的循环,使i和/或j大于100

Change it on this. 对此进行更改。

    public void firstFor(int index){
      for(int i =index; i<100;i++){
      secondFor();
      }
  }
    public void secondFor(){
      for(int j=0;j<100;j++){
    //your code...
       if(code==true) return;

      }
  }

Put your code block in a separate method and use return. 将您的代码块放在单独的方法中,然后使用return。 It will be the cleanest approach. 这将是最干净的方法。

You can use label: 您可以使用标签:

  firstLabel: for (int i = 0; i < 100; i++) {
            secondLabel: for (int j = 10; j < 100; j++) {
                System.out.println("J = " + j);
                if (j == 50) {
                    break firstLabel;
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM