Break in nested for loops

43,452

Solution 1

It breaks only the inner loop, and therefore does what you want. To break more than one level, in Java, you can use a "labelled break" like so:

schiffe_loop:
for(int i = 0; i < schiffe.length-1; i++){
    some_stuff();
    for(int k = 0; k < stationen.length-1; k++){
        if (something_really_bad_happened()) {
            break schiffe_loop;
        }
    }
}

But usually you will not need this.

You may consider making a separate method for the inner loop anyway; it's something you can easily give a name to ("find_available_station" or something like that), and will probably need somewhere else.

Also, please be aware that your loops right now will miss the last element of each array. Think carefully about why you are using < instead of <=; it's exactly so that you use every value from 0 up to but not including the specified one.

Solution 2

break will break the innermost loop, in your case 2nd loop.

To make it break the outer loop you can use a labeled break as:

OUTER:for(...) {
         for(...) {
            break OUTER;
         }
      }

Solution 3

break only breaks out of the innermost loop.

Solution 4

Break statement terminates the closest enclosing loop or switch statement in which it appears in many languages but you can try it and be sure 100%.

Solution 5

put the inner two loops in a function and use return to break out of both of them.

Share:
43,452
DarkLeafyGreen
Author by

DarkLeafyGreen

Tackling Complexity in the Heart of Software

Updated on July 09, 2022

Comments

  • DarkLeafyGreen
    DarkLeafyGreen almost 2 years

    Possible Duplicate:
    How to Break from main/outer loop in a double/nested loop?

    I have the following situation:

          for(int i = 0; i < schiffe.length-1; i++){
                if(schiffe[i].schaden){
                    schlepper.fliege(schiffe[i].x, 
                                     schiffe[i].y, 
                                     schiffe[i].z);
                    schlepper.wirdAbgeschleppt = schiffe[i];
                    for(int k = 0; k < stationen.length-1; k++){
                        if(stationen[k].reparatur == null){
                            schlepper.fliege(stationen[k].x,
                                             stationen[k].y,
                                             stationen[k].z);
                            break;
                        }
                    }
                }
            }
    

    I want to

    schlepper.fliege(stationen[k].x,
                     stationen[k].y,
                     stationen[k].z);
    

    be performed once and then break out of the inner loop and continue with the for(int i... loop. So I used a break in my code. But I am not really sure if this is right. Does the break cause a break for all loops or just for the second loop?