Method 1: Label: define a label before the outer loop statement, and then use the break statement with the label in the inner loop body code. The label is used to jump out of the multi-layer nested loop. You can use the label label to mark which statement you want to exit. Specifies that the label must precede the loop (meaning that the loop must follow the label). We can only use goto for similar functions in C ා. Although Java retains goto keywords, it is not allowed to use (goto is reserved word). Note that there can be no other code between the label and the following loop statement. The label applies to both break and continue. From a design point of view, it is not a good idea to use label or goto.
public class OutLoopWithLabel{ public static void main(String args[]) { ok: // Set a label to jump out of the current loop. Note that ok is followed by a colon: for (int i = 0; i < 10; i++) { for (int j = 0; j <= 10; j++) { System.out.println("i=" + i + ",j=" + j); if (j == 5) break ok; // Set a label to jump out of the current loop } } } }
Method 2: combination of Boolean and break: through the combination of Boolean conditional variable and break, the inner loop changes the conditional variable before the break, and the outer loop ends the outer loop when the condition variable changes.
public class OutLoopWithBooleanBreak { public static void main(String args[]) { int arr[][] = { { 1, 2, 3 }, { 4, 5, 6, 7 }, { 9 } }; boolean found = false; System.out.println("arr.length " + arr.length); for (int i = 0; i < arr.length && !found; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.println("i=" + i + ",j=" + j); if (arr[i][j] == 5) { found = true; // Modified the parameter found in the first loop break; // Jump out of circulation } } } } }
Method 3: return: directly jump out of the whole method in the inner loop.
public class OutLoopWithReturn { public static void main(String[] args) { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (i * j > 60) { return; } System.out.println(i + " * " + j + " = " + (i * j)); } } } }
Method 4: throw Exception: throw an exception directly in the inner loop.
public class OutLoopWithException { public static void main(String[] args) throws Exception { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (i * j > 60) { throw new Exception("exception"); } System.out.println(i + " * " + j + " = " + (i * j)); } } } }