在Java中打破嵌套的for循环

Breaking out of nested for loops in Java

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Breaking out of nested loops in Java

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

假设我有一个场景让我想起以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
            ...
        }
        ...
    }
}


使用标签,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
        ...
    }
    ...
}

}

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

如@peter所指出的,如果您希望尽早完成当前的外部迭代并继续到下一个迭代,则使用continue outer;,而不是从while循环中退出。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
loop:
while(condition) {
// want to return to this point
for (Integer x : xs) {
    continue loop:
    for (Integer y : ys) {
        continue loop:
        ...
    }
    ...
}
for (Integer a : as) {
    for (Integer b : bs) {
        continue loop:
        ...
    }
    ...
}

}


用语法标记循环

LABEL: LoopType以后,您可以使用break语句退出break LABEL;的某个循环。

1
2
3
4
5
6
7
OUT: while(somecond){
IN:for(...) {
   INNER: for(...){
break IN;// will get you outta IN and INNER for loop
}
 }
}

你可以这样做:

1
2
3
4
5
6
7
8
here:
while(condition) {
   for (Integer x : xs) {
        // point 1
        for (Integer y : ys) {
            break here;
        }
    }

在Java规范中描述了带有或不带标签的中断语句:

A break statement with no label attempts to transfer control to the
innermost enclosing switch, while, do, or for statement of the
immediately enclosing method or initializer; this statement, which is
called the break target, then immediately completes normally.

A break statement with label Identifier attempts to transfer control
to the enclosing labeled statement (§14.7) that has the same
Identifier as its label; this statement, which is called the break
target, then immediately completes normally. In this case, the break
target need not be a switch, while, do, or for statement.


您可以这样做:stackoverflow.com/questions/886955/breaking-out-of-nested-loops-in-java处理相同的问题。


是的,您可以使用带标签的break语句:

1
2
3
SOME_LABEL:
   // ... some code here
   break SOME_LABEL;

谨慎使用,这是一种突破多个嵌套循环的干净方法。