How do I break out of nested loops in Java?

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

    It's fairly easy to use label, You can break the outer loop from inner loop using the label, Consider the example below,

    public class Breaking{
        public static void main(String[] args) {
            outerscope:
            for (int i=0; i < 5; i++) {
                for (int j=0; j < 5; j++) {
                    if (condition) {
                        break outerscope;
                    }
                }
            }
        }
    }
    

    Another approach is to use the breaking variable/flag to keep track of required break. consider the following example.

    public class Breaking{ 
        public static void main(String[] args) {
            boolean isBreaking = false;
            for (int i=0; i < 5; i++) {
                for (int j=0; j < 5; j++) {
                    if (condition) {
                        isBreaking = true;
                        break;
                    }
                }
                if(isBreaking){
                    break;
                }
            }
        }
    }
    

    However, I prefer using the first approach.

提交回复
热议问题