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 |
使用标签,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
}
然后您可以使用
如@peter所指出的,如果您希望尽早完成当前的外部迭代并继续到下一个迭代,则使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
}
用语法标记循环
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 |
在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处理相同的问题。
是的,您可以使用带标签的
1 2 3 | SOME_LABEL: // ... some code here break SOME_LABEL; |
谨慎使用,这是一种突破多个嵌套循环的干净方法。