To break out of nested loops in Java, you can use a labeled break statement. This allows you to specify the loop you want to break out of by labeling it with a user-defined label. Here's an example:
java
public class NestedLoopBreakExample {
public static void main(String[] args) {
outerLoop: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i: " + i + ", j: " + j);
if (i == 2 && j == 2) {
System.out.println("Breaking out of both loops.");
break outerLoop; // This will break out of the outer loop
}
}
}
}
}
In this example, the outerLoop
label is applied to the outer loop. When the condition (i == 2 && j == 2)
is met, the break outerLoop;
statement is executed, which breaks out of both the inner and outer loops.
Keep in mind that using labeled breaks should be done sparingly, as they can make the code less readable and harder to understand. In most cases, it's better to refactor your code to use other control structures, such as using a flag variable to control loop termination or redesigning the loop logic to make breaking unnecessary.
Comments
Post a Comment