[英]How do I break from the main/outer loop in a double/nested loop? [duplicate]
这个问题在这里已有答案:
如果我在循环中循环并且一旦if
语句满足我想要打破主循环,我该怎么做呢?
这是我的代码:
for (int d = 0; d < amountOfNeighbors; d++) {
for (int c = 0; c < myArray.size(); c++) {
if (graph.isEdge(listOfNeighbors.get(d), c)) {
if (keyFromValue(c).equals(goalWord)) { // Once this is true I want to break main loop.
System.out.println("We got to GOAL! It is "+ keyFromValue(c));
break; // This breaks the second loop, not the main one.
}
}
}
}
使用带标签的休息:
mainloop:
for(){
for(){
if (some condition){
break mainloop;
}
}
}
另见
您可以为循环添加标签,并使用带labelled break
来跳出适当的循环: -
outer: for (...) {
inner: for(...) {
if (someCondition) {
break outer;
}
}
}
有关更多信息,请参阅以下链接
您可以从该函数return
控件。 或者使用丑陋的break labels
方法:)
如果在for
语句后面还有另一个代码部分,则可以在函数中重构循环。
IMO,在OOP中应该不鼓励使用中断和继续,因为它们会影响可读性和维护。 当然,有些情况下它们很方便,但总的来说我认为我们应该避免使用它们,因为它们会鼓励使用goto风格的编程。
显然,这个问题的变化很多。 彼得在这里使用标签提供了一些好的和奇怪的用途
看起来对于Java而言,标记的中断似乎是要走的路(基于其他答案的共识)。
但是对于许多(大多数?)其他语言,或者如果你想避免任何像控制流那样的goto
,你需要设置一个标志:
bool breakMainLoop = false;
for(){
for(){
if (some condition){
breakMainLoop = true;
break;
}
}
if (breakMainLoop) break;
}
纯娱乐:
for(int d = 0; d < amountOfNeighbors; d++){
for(int c = 0; c < myArray.size(); c++){
...
d = amountOfNeighbors;
break;
...
}
// No code here
}
对break label
评论:这是一个前锋goto。 它可以打破任何声明并跳转到下一个:
foo: // Label the next statement (the block)
{
code ...
break foo; // goto [1]
code ...
}
//[1]
对于初学者来说,最好和最简单的方法是:
outerloop:
for(int i=0; i<10; i++){
// Here we can break the outer loop by:
break outerloop;
innerloop:
for(int i=0; i<10; i++){
// Here we can break innerloop by:
break innerloop;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.