Tag Archives: Java syntax

The method of Java jumping out of loop

said in the previous sentence:

Today, when writing a program, I need to jump out of the loop. I can’t remember, but I checked online, as follows:

as you know, in Java, if you want to break out of a for loop, there are generally two ways: break and continue.

break is a break out of the current for loop, as shown in the following code:

package com.xtfggef.algo; 
 
public class RecTest { 
 
    /**
     * @param args
     */ 
    public static void main(String[] args) { 
        for(int i=0; i<10; i++){ 
            if(i==5){ 
                break; 
            } 
            System.out.print(i+" "); 
        } 
    } 
} 

output: 0 1 2 3 4

means that the break breaks out of the current loop.

continue is to break out of the current loop and open the next loop, as shown below:

package com.xtfggef.algo; 
 
public class RecTest { 
 
    /**
     * @param args
     */ 
    public static void main(String[] args) { 
        for (int i = 0; i < 10; i++) { 
            if (i == 5) { 
                continue; 
            } 
            System.out.print(i+" "); 
        } 
    } 
} 

output: 0 1 2 3 4 6 7 8 9

jump out of a multi-layer loop

the above two methods cannot jump out of a multi-layer loop. If you need to jump out of a multi-layer loop, you need to use a label, define a label, and then you need to jump

, use the break label line, the code is as follows:

package com.xtfggef.algo; 
 
public class RecTest { 
 
    /**
     * @param args
     */ 
    public static void main(String[] args) { 
 
        loop: for (int i = 0; i < 10; i++) { 
            for (int j = 0; j < 10; j++) { 
                for (int k = 0; k < 10; k++) { 
                    for (int h = 0; h < 10; h++) { 
                        if (h == 6) { 
                            break loop; 
                        } 
                        System.out.print(h); 
                    } 
                } 
            } 
        } 
        System.out.println("\nI'm here!"); 
    } 
}

Output:

012345

I’m here!

the meaning is obvious!