问题

我有这样的嵌套循环结构:

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

现在我怎么能摆脱两个循环。我看过类似的问题,但没有一个关于Java。由于大多数使用gotos,我无法应用这些解决方案。

我不想将内部循环置于不同的方法中。

更新:当我完成循环块的执行时,我不想重新运行循环。


#1 热门回答(2067 赞)

像其他答复者一样,我会definitelypreferto以不同的方式放置内部循环。这个答案只是说明如何满足问题中的要求。

你可以使用`break'和外部循环的标签。例如:

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");
    }
}

这打印:

0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
Breaking
Done

#2 热门回答(368 赞)

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

这将为可读性带来回报。

代码会变成这样的:

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);
            }
        }
    }
}

#3 热门回答(186 赞)

您可以在循环中使用命名块:

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

原文链接