Câu hỏi phỏng vấn Java
Câu hỏi

How do I break out of nested loops in Java?

Câu trả lời

To break out of nested loops in Java, you have several methods at your disposal, each suitable for different scenarios and coding styles.

Using Labeled Break

The most straightforward method to break out of nested loops is to use a labeled break. You can label the outer loop and then use the break statement with the label to exit both the inner and outer loops when a certain condition is met. Here’s how you can implement it:

public class Main {
    public static void main(String[] args) {
        outer: for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    break outer;
                }
                System.out.println("i = " + i + ", j = " + j);
            }
        }
    }
}

In this example, the loop is labeled outer, and when i equals 2 and j equals 2, the break outer; statement is executed, which terminates all iterations of both the inner and outer loops[1][2][3][5].

Using Return in a Method

Another approach is to encapsulate the nested loops within a method and use a return statement to exit from all loops at once. This method enhances readability and maintainability:

public class Main {
    public static int breakNestedLoops() {
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                int product = i * j;
                if (product == 8) {
                    return product;
                }
            }
        }
        return -1; // Return a default value indicating no break occurred
    }

    public static void main(String[] args) {
        System.out.println(breakNestedLoops());
    }
}

He...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What's the advantage of using getters and setters?

middle

When is the finalize() called? What is the purpose of finalization?

expert

What does synchronized mean?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào