How do I break out of nested loops in Java?

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

    I needed to do a similar thing, but I chose not to use the enhanced for loop to do it.

    int s = type.size();
    for (int i = 0; i < s; i++) {
        for (int j = 0; j < t.size(); j++) {
            if (condition) {
                // do stuff after which you want 
                // to completely break out of both loops
                s = 0; // enables the _main_ loop to terminate
                break;
            }
        }
    }
    

提交回复
热议问题