39

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.
            }
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shepard
  • 1,111
  • 5
  • 16
  • 32

6 Answers6

61

Using a labeled break:

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

Also See

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jmj
  • 237,923
  • 42
  • 401
  • 438
  • Awesome! I learnt something new. I thought labels were for days gone by (remember GW-BASIC?). I would have used boolean flags for this, but labels are much cooler! – ADTC Oct 25 '12 at 16:47
  • @ADTC GW-BASIC never supported textual labels, only numerical line numbers (and it required those). IIRC, coming out of Microsoft it was QuickBASIC that added support for textual labels, as well as named subroutines. QBasic certainly included such support if Wikipedia is to be trusted, at least no later than Visual Basic. – user Oct 26 '12 at 07:27
28

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:

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
12

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dan
  • 13,132
  • 3
  • 38
  • 49
  • 2
    Source/defend your claim that labels are ugly – John Dvorak Oct 25 '12 at 16:46
  • 5
    In this particular case, return may be appropriate. However labels are not ugly and often useful. – Colin D Oct 25 '12 at 16:47
  • 2
    @JanDvorak Thanks, ugly and hard to debug. – dan Oct 25 '12 at 16:47
  • 1
    I disagree. They are not harder to debug and shouldn't be hard to understand either. I don't consider them ugly at all. – John Dvorak Oct 25 '12 at 16:49
  • @JanDvorak I agree, probably hard was too strong :). I was trying to say that it's easier to read a code without goto logic. – dan Oct 25 '12 at 16:51
  • 2
    (I generally find some languages unbearably hard to read for other reasons - I can't even recall the last time I used explicit "double loops" that required breaking in a language that had proper HoF support and a supportive collection APIs. This would be much more cleanly written in terms of an "Any" function, IMOHO ;-) –  Oct 25 '12 at 16:52
  • @pst I agree. Using a function will help him properly maintain and reuse the code, at least. – dan Oct 25 '12 at 16:54
  • 3
    IMO, it's good to rethink about how to write the code again to avoid labled loops. The reason why so many people don't know that they exist is because we don't need them. I am not saying they are always bad. – Bhesh Gurung Oct 25 '12 at 16:58
  • @BheshGurung That was what I was trying to suggest with my answer too, but it seems that many are still used to the goto logic :) – dan Oct 25 '12 at 17:01
3

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thymine
  • 8,775
  • 2
  • 35
  • 47
  • If a labelled break really is the way to go in Java, then the way to go in C/C++ is a goto. – Evan Harper Oct 26 '12 at 00:38
  • Also, the question is clearly labelled as `java`. – user Oct 26 '12 at 07:29
  • 1
    Doesn't change the fact that someone searching for 'break nested loop' might come upon it. @EvanHarper I would agree with that line of reasoning, but I haven't spent much time in Java so just went with the consensus of the other answers... – Thymine Oct 26 '12 at 17:03
2

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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
irreputable
  • 44,725
  • 9
  • 65
  • 93
0

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;
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Keshav bansal
  • 130
  • 1
  • 2