How do I break out of nested loops in Java?

前端 未结 30 2752
梦毁少年i
梦毁少年i 2020-11-21 11:51

I\'ve got a nested loop construct like this:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do somethin         


        
30条回答
  •  有刺的猬
    2020-11-21 12:15

    If it's a new implementation, you can try rewriting the logic as if-else_if-else statements.

    while(keep_going) {
    
        if(keep_going && condition_one_holds) {
            // Code
        }
        if(keep_going && condition_two_holds) {
            // Code
        }
        if(keep_going && condition_three_holds) {
            // Code
        }
        if(keep_going && something_goes_really_bad) {
            keep_going=false;
        }
        if(keep_going && condition_four_holds) {
            // Code
        }
        if(keep_going && condition_five_holds) {
            // Code
        }
    }
    

    Otherwise you can try setting a flag when that special condition has occured and check for that flag in each of your loop-conditions.

    something_bad_has_happened = false;
    while(something is true && !something_bad_has_happened){
        // Code, things happen
        while(something else && !something_bad_has_happened){
            // Lots of code, things happens
            if(something happened){
                -> Then control should be returned ->
                something_bad_has_happened=true;
                continue;
            }
        }
        if(something_bad_has_happened) { // The things below will not be executed
            continue;
        }
    
        // Other things may happen here as well, but they will not be executed
        //  once control is returned from the inner cycle.
    }
    

    HERE! So, while a simple break will not work, it can be made to work using continue.

    If you are simply porting the logic from one programming language to Java and just want to get the thing working you can try using labels.

提交回复
热议问题