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

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 earlyExit = false;
for(int i = 0 ; i < 10 && !earlyExit; i++) {
     for(int j = 0 ; i < 10 && !earlyExit; j++) { earlyExit = true; }
}

其他回答

您可以执行以下操作:

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

在某些情况下,我们可以在这里有效地使用while循环。

Random rand = new Random();
// Just an example
for (int k = 0; k < 10; ++k) {
    int count = 0;
    while (!(rand.nextInt(200) == 100)) {
       count++;
    }

    results[k] = count;
}

我从不使用标签。这似乎是一种不好的做法。我会这样做:

boolean finished = false;
for (int i = 0; i < 5 && !finished; i++) {
    for (int j = 0; j < 5; j++) {
        if (i * j > 6) {
            finished = true;
            break;
        }
    }
}

我需要做类似的事情,但我选择不使用增强的for循环来做。

int s = type.size();
for (int i = 0; i < s; i++) {
    for (int j = 0; j < t.size(); j++) {
        if (condition) {
            // do stuff after which you want 
            // to completely break out of both loops
            s = 0; // enables the _main_ loop to terminate
            break;
        }
    }
}

另一个解决方案,没有举例说明(它实际上在产品代码中有效)。

try {
    for (Type type : types) {
        for (Type t : types2) {
            if (some condition #1) {
                // Do something and break the loop.
                throw new BreakLoopException();
            }
        }
    }
}
catch (BreakLoopException e) {
    // Do something on look breaking.
}

当然,BreakLoopException应该是内部的、私有的、加速的,没有堆栈跟踪:

private static class BreakLoopException extends Exception {
    @Override
    public StackTraceElement[] getStackTrace() {
        return new StackTraceElement[0];
    }
}