How do I break out of nested loops in Java?

前端 未结 30 2771
梦毁少年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:10

    You can use a temporary variable:

    boolean outerBreak = false;
    for (Type type : types) {
       if(outerBreak) break;
        for (Type t : types2) {
             if (some condition) {
                 // Do something and break...
                 outerBreak = true;
                 break; // Breaks out of the inner loop
             }
        }
    }
    

    Depending on your function, you can also exit/return from the inner loop:

    for (Type type : types) {
        for (Type t : types2) {
             if (some condition) {
                 // Do something and break...
                 return;
             }
        }
    }
    

提交回复
热议问题