我有一个这样的嵌套循环构造:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do something and break...
             break; // Breaks out of the inner loop
         }
    }
}

现在我怎样才能打破这两个循环?我已经研究过类似的问题,但没有一个与Java相关。我无法应用这些解决方案,因为大多数人都使用goto。

我不想将内部循环放在不同的方法中。

我不想返回循环。当中断时,我完成了循环块的执行。


当前回答

for(int j=0;j<5;j++)//内部循环应替换为对于(int j=0;j<5&&!exitloops;j++)。

这里,在这种情况下,如果条件为True,则应退出完整的嵌套循环。但如果我们只对上循环使用exitloops

 for (int i = 0; i < 5 && !exitloops; i++) //upper loop

然后,内部循环将继续,因为并没有额外的标志通知此内部循环退出。

示例:如果i=3和j=2,则条件为假。但在下一次内循环迭代中,j=3,则条件(i*j)变为9,这是真的,但内循环将继续,直到j变为5。

因此,它也必须对内部循环使用exitloops。

boolean exitloops = false;
for (int i = 0; i < 5 && !exitloops; i++) { //here should exitloops as a Conditional Statement to get out from the loops if exitloops become true. 
    for (int j = 0; j < 5 && !exitloops; j++) { //here should also use exitloops as a Conditional Statement. 
        if (i * j > 6) {
            exitloops = true;
            System.out.println("Inner loop still Continues For i * j is => "+i*j);
            break;
        }
        System.out.println(i*j);
    }
}

其他回答

标记中断概念用于中断java中的嵌套循环,通过使用标记中断,您可以在任何位置中断循环的嵌套。示例1:

loop1:
 for(int i= 0; i<6; i++){
    for(int j=0; j<5; j++){
          if(i==3)
            break loop1;
        }
    }

假设有3个循环,您希望终止循环3:示例2:

loop3: 
for(int i= 0; i<6; i++){
loop2:
  for(int k= 0; k<6; k++){
loop1:
    for(int j=0; j<5; j++){
          if(i==3)
            break loop3;
        }
    }
}

Demo

public static void main(String[] args) {
    outer:
    while (true) {
        while (true) {
            break outer;
        }
    }
}

您可以在不使用任何标签:和标志的情况下断开所有循环。

这只是一个棘手的解决方案。

这里条件1是用于从循环K和J中断的条件。条件2是用于从循环K、J和I中分离的条件。

例如:

public class BreakTesting {
    public static void main(String[] args) {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                for (int k = 0; k < 9; k++) {
                    if (condition1) {
                        System.out.println("Breaking from Loop K and J");
                        k = 9;
                        j = 9;
                    }
                    if (condition2) {
                        System.out.println("Breaking from Loop K, J and I");
                        k = 9;
                        j = 9;
                        i = 9;
                    }
                }
            }
        }
        System.out.println("End of I , J , K");
    }
}

如果有人在寻找添加标记循环的kotlin方法

loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop
    }
}

来源

使用函数:

public void doSomething(List<Type> types, List<Type> types2){
  for(Type t1 : types){
    for (Type t : types2) {
      if (some condition) {
         // Do something and return...
         return;
      }
    }
  }
}