How do I break out of nested loops in Java?

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

    for (int j = 0; j < 5; j++) //inner loop should be replaced with for (int j = 0; j < 5 && !exitloops; j++).

    Here, in this case complete nested loops should be exit if condition is True . But if we use exitloops only to the upper loop

     for (int i = 0; i < 5 && !exitloops; i++) //upper loop
    

    Then inner loop will continues, because there is no extra flag that notify this inner loop to exit.

    Example : if i = 3 and j=2 then condition is false. But in next iteration of inner loop j=3 then condition (i*j) become 9 which is true but inner loop will be continue till j become 5.

    So, it must use exitloops to the inner loops too.

    boolean exitloops = false;
    for (int i = 0; i < 5 && !exitloops; i++) { //here should exitloops as a Conditional Statement to get out from the loops if exitloops become true. 
        for (int j = 0; j < 5 && !exitloops; j++) { //here should also use exitloops as a Conditional Statement. 
            if (i * j > 6) {
                exitloops = true;
                System.out.println("Inner loop still Continues For i * j is => "+i*j);
                break;
            }
            System.out.println(i*j);
        }
    }
    

提交回复
热议问题