Break in nested for loops

Upvote picture Upvote · Dec 2, 2010 · Viewed 42.9k times · Source

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?

Answer

Karl Knechtel picture Karl Knechtel · Dec 2, 2010

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.