How do I break from the main/outer loop in a doubl

2019-01-17 05:37发布

This question already has an answer here:

If I have loop in a loop and once an if statement is satisfied I want to break main loop, how am I supposed to do that?

This is my code:

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.
            }
        }
    }
}

6条回答
该账号已被封号
2楼-- · 2019-01-17 06:29

Just for fun:

for(int d = 0; d < amountOfNeighbors; d++){
    for(int c = 0; c < myArray.size(); c++){
        ...
            d = amountOfNeighbors;
            break;
        ...
    }
    // No code here
}

Comment on break label : it's a forward goto. It can break any statement and jump to the next:

foo: // Label the next statement (the block)
{
    code ...
    break foo;  // goto [1]
    code ...
}

//[1]
查看更多
来,给爷笑一个
3楼-- · 2019-01-17 06:33

It looks like for Java a labeled break appears to be the way to go (based on the consensus of the other answers).

But for many (most?) other languages, or if you want to avoid any goto like control flow, you need to set a flag:

bool breakMainLoop = false;
for(){
    for(){
        if (some condition){
            breakMainLoop = true;
            break;
        }
    }
    if (breakMainLoop) break;
}
查看更多
放荡不羁爱自由
4楼-- · 2019-01-17 06:37

You can just return the control from that function. Or use the ugly break labels approach :)

If there is another code parts after your for statement, you can refactor the loops in a function.

IMO, the use of breaks and continue should be discouraged in OOP, since they affect the readability and the maintenance. Sure, there are cases where they are handy, but in general I think that we should avoid them, since they will encourage the use of goto style programing.

Apparently variations to this questions are posted a lot. Here Peter provided some good and odd uses using labels.

查看更多
太酷不给撩
5楼-- · 2019-01-17 06:40

You can add labels to your loop, and use that labelled break to break out of the appropriate loop: -

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

See these links for more information:

查看更多
Anthone
6楼-- · 2019-01-17 06:41

The best and easy methods for beginners even:

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;
    }
}
查看更多
聊天终结者
7楼-- · 2019-01-17 06:43

Using a labeled break:

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

Also See

查看更多
登录 后发表回答