39

如果我在一个循环中有循环并且一旦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.
            }
        }
    }
}
4

6 回答 6

61

使用带标签的中断:

mainloop:
for(){
 for(){
   if (some condition){
     break mainloop;
   }
  }
}

另见

于 2012-10-25T16:44:11.927 回答
28

您可以在循环中添加标签,并使用它labelled break来打破适当的循环:-

outer: for (...) {
    inner: for(...) {
        if (someCondition) {
            break outer;
        }
    }
}

有关更多信息,请参阅这些链接:

于 2012-10-25T16:44:03.770 回答
12

您可以return从该功能中进行控制。或者使用丑陋的break labels方法:)

如果您的语句之后还有其他代码部分for,您可以重构函数中的循环。

IMO,不鼓励在 OOP 中使用中断和继续,因为它们会影响可读性和维护。当然,在某些情况下它们很方便,但总的来说我认为我们应该避免它们,因为它们会鼓励使用 goto 样式编程。

显然,这个问题的变化已经发布了很多。在这里,彼得使用标签提供了一些好的和奇怪的用途。

于 2012-10-25T16:45:03.787 回答
3

对于 Java 来说,标记中断似乎是要走的路(基于其他答案的共识)。

但是对于许多(大多数?)其他语言,或者如果你想避免任何goto类似的控制流,你需要设置一个标志:

bool breakMainLoop = false;
for(){
    for(){
        if (some condition){
            breakMainLoop = true;
            break;
        }
    }
    if (breakMainLoop) break;
}
于 2012-10-25T20:55:34.210 回答
2

纯娱乐:

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]
于 2012-10-25T16:54:28.763 回答
0

对于初学者来说最好和最简单的方法:

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;
    }
}
于 2015-08-23T21:10:47.563 回答