在Java中打破嵌套的for循环

Fro*_*koy 2 java loops for-loop break while-loop

可能重复:
在Java中突破嵌套循环

我如何使用break和/或continue语句返回到第1,2和3点的while循环的第一行,例如,如伪代码所示?

假设我有一个让人联想到以下内容的场景:

while(condition) {
    // want to return to this point
    for (Integer x : xs) {
        // point 1
        for (Integer y : ys) {
            // point 2
            ...
        }
        ...
    }
    for (Integer a : as) {
        for (Integer b : bs) {
            // point 3
            ...
        }
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*ius 5

使用如下标签:

outer:
while(condition) {
// want to return to this point
for (Integer x : xs) {
    // point 1
    for (Integer y : ys) {
        // point 2
        ...
    }
    ...
}
for (Integer a : as) {
    for (Integer b : bs) {
        // point 3
        ...
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

}

然后你可以break outer;用来逃避while循环.这也适用于嵌套的for循环,但我尽量不要过度使用标签

正如@Peter所指出的那样,continue outer;如果你希望尽早完成当前的外部迭代并继续下一个迭代,则使用,而不是转义while循环.