How do I break out of nested loops in Java?

前端 未结 30 2821
梦毁少年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 12:07

    You can do the following:

    1. set a local variable to false

    2. set that variable true in the first loop, when you want to break

    3. then you can check in the outer loop, that whether the condition is set then break from the outer loop as well.

      boolean isBreakNeeded = false;
      for (int i = 0; i < some.length; i++) {
          for (int j = 0; j < some.lengthasWell; j++) {
              //want to set variable if (){
              isBreakNeeded = true;
              break;
          }
      
          if (isBreakNeeded) {
              break; //will make you break from the outer loop as well
          }
      }
      

提交回复
热议问题