Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break in nested for loops [duplicate]

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?

like image 529
UpCat Avatar asked Dec 02 '10 06:12

UpCat


People also ask

What happens if you break in a nested loop?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

Does break break for loops?

Description. break terminates the execution of a for or while loop.


1 Answers

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.

like image 82
Karl Knechtel Avatar answered Sep 20 '22 13:09

Karl Knechtel