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

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

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

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

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


当前回答

boolean broken = false; // declared outside of the loop for efficiency
for (Type type : types) {
    for (Type t : types2) {
        if (some condition) {
            broken = true;
            break;
        }
    }

    if (broken) {
        break;
    }
}

其他回答

boolean condition = false;
for (Type type : types) {
    for (int i = 0; i < otherTypes.size && !condition; i ++) {
        condition = true; // If your condition is satisfied
    }
}

将条件用作完成处理时的标志。然后,内部循环仅在条件未满足时继续。无论哪种方式,外环都会继续发出嗡嗡声。

如果您不喜欢中断和gotos,可以使用“传统”for循环,而不是for in,并附加一个中止条件:

int a, b;
bool abort = false;
for (a = 0; a < 10 && !abort; a++) {
    for (b = 0; b < 10 && !abort; b++) {
        if (condition) {
            doSomeThing();
            abort = true;
        }
    }
}

最佳且简单的方法。。

outerloop:
for(int i=0; i<10; i++){
    // here we can break Outer loop by 
    break outerloop;

    innerloop:
    for(int i=0; i<10; i++){
        // here we can break innerloop by 
        break innerloop;
     }
}

您可以执行以下操作:

将局部变量设置为false当您想中断时,在第一个循环中将该变量设置为true然后可以在外循环中检查是否设置了条件,然后也可以从外循环中断开。布尔isBreakNeeded=false;对于(int i=0;i<some.length;i++){对于(int j=0;j<some.lengthasWell;j++){//要设置变量if(){isBreakNeeded=true;打破}if(isBreakNeed){断裂//也会让你脱离外环}}

你只需要使用标签来打破内部循环

public class Test {
public static void main(String[] args) {
    outerloop:
for (int i=0; i < 5; i++) {
  for (int j=0; j < 5; j++) {
    if (i * j > 6) {
      System.out.println("Breaking");
      break outerloop;
    }
    System.out.println(i + " " + j);
  }
}
System.out.println("Done");
}
}