简体   繁体   中英

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. The reason for this is that I get a problem later in my program when using the break statement.

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. Better yet, extract the loops into another method and use return statement, as @SR SH mentioned.

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.

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. 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;
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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