How to break out of multiple nested loops in Java?

  In Java, to break out of multiple nested loops, you can use a labeled break statement. By adding a label before the outer loop, and then using the break statement followed by the label name in the inner loop, the purpose of jumping out of multiple loops can be achieved.

  The following is sample code for breaking out of multiple nested loops using labels and break statements:

public class NestedLoopExample {
    public static void main(String[] args) {
        // 定义一个标签 "outerLoop"
        outerLoop:
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.println("i = " + i + ", j = " + j);

                if (i == 3 && j == 2) {
                    // 当 i=3 且 j=2 时,跳出外层循环
                    break outerLoop;
                }
            }
        }
    }
}

  In this example we have two nested for loops, the outer loop i goes from 1 to 5 and the inner loop j goes from 1 to 3. We define a label called outerLoop and place it before the outer loop.

1690508031387_How to jump out of multi-layer nested loops in Java.jpg

  When i is equal to 3 and j is equal to 2, we use the break outerLoop; statement to break out of the outer loop with the label outerLoop. This will cause the program to not execute the remaining iterations of the outer loop and continue executing the code following the label.

  The output will be:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2

  When the execution reaches i=3 and j=2, the outer loop will be jumped out because we used the break outerLoop; statement.

  It should be noted that using labels and break statements can help us gracefully break out of multiple nested loops under certain conditions. However, abuse of this method may lead to unclear code logic. It is recommended to avoid excessive nesting and complex control structures to improve the readability and maintainability of the code.

 

Guess you like

Origin blog.csdn.net/Blue92120/article/details/131974070