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

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

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

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

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


当前回答

您可以执行以下操作:

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

其他回答

非常不寻常的方法,但就代码长度(而不是性能)而言,这是您可以做的最简单的事情:

for(int i = 0; i++; i < j) {
    if(wanna exit) {
        i = i + j; // if more nested, also add the 
                   // maximum value for the other loops
    }
}

在某些情况下,我们可以在这里有效地使用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;
}

我需要做类似的事情,但我选择不使用增强的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;
        }
    }
}

使用标签非常简单,您可以使用标签将外循环与内循环分开,请考虑下面的示例,

public class Breaking{
    public static void main(String[] args) {
        outerscope:
        for (int i=0; i < 5; i++) {
            for (int j=0; j < 5; j++) {
                if (condition) {
                    break outerscope;
                }
            }
        }
    }
}

另一种方法是使用中断变量/标志来跟踪所需的中断。考虑以下示例。

public class Breaking{ 
    public static void main(String[] args) {
        boolean isBreaking = false;
        for (int i=0; i < 5; i++) {
            for (int j=0; j < 5; j++) {
                if (condition) {
                    isBreaking = true;
                    break;
                }
            }
            if(isBreaking){
                break;
            }
        }
    }
}

然而,我更喜欢使用第一种方法。

从技术上讲,正确的答案是标记外循环。在实践中,如果您想在内部循环中的任何点退出,那么最好将代码外部化为方法(如果需要的话是静态方法),然后调用它。

这将有助于提高可读性。

代码会变成这样:

private static String search(...) 
{
    for (Type type : types) {
        for (Type t : types2) {
            if (some condition) {
                // Do something and break...
                return search;
            }
        }
    }
    return null; 
}

匹配接受答案的示例:

 public class Test {
    public static void main(String[] args) {
        loop();
        System.out.println("Done");
    }

    public static void loop() {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (i * j > 6) {
                    System.out.println("Breaking");
                    return;
                }
                System.out.println(i + " " + j);
            }
        }
    }
}