Now, in Java, if you want to jump out of a for loop, there are generally two ways to do this: break and continue.
Break is to jump out of the current for loop, as shown in the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Public class Rectest { /** * @param args */ public static void Main (String[] args) { for(int i=0; i< ; i++) { if(i==5) { break; } System.out.print (i+""); } } } Output:0 1 2 3 4 |
In other words, break jumps out (terminates) the current loop. Continue is to jump out of the current loop and start the next loop as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Public class Rectest { /** * @param args */ public static void Main (String[] args) { for (int i = 0; i < i++) { if (i = = 5) { continue; } System.out.print (i+""); } } } Output:0 1 2 3 4 6 7 8 9 |
The above two methods do not jump out of the multilayer loop, if you need to jump out of the multi-layer loop, you need to use a label, define a label tag, and then where you need to jump, with the break label on the line, the code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21st 22 23 24 25 26 |
Public class Rectest { /** * @param args */ public static void Main (String[] args) { Loop: for (int i = 0; i < i++) { for (int j = 0; j < ; j + +) { for (int k = 0; k < k++) { for (int h = 0; h < h++) { if (h = = 6) { break Loop; } System.out.print (h); } } } } System.out.println ("\ni ' m here!" ); } } Output: 012345 I ' m here! |
Want to learn more about Java, you can click on the small peak online Java 0 Foundation ? To learn. More Java Learning courses, you can focus on e mentor .
Ways to jump out of a for loop in Java