There are three jump structures in java: break continue return
break: used to exit from any statement block.
1. It ends the entire loop and jumps to the end of the loop;
eg: Outputs a loop from 1 to 10, but stops when it is greater than 2 and a multiple of 3
Java code
public static void main(String[] args){ for(int i=1;i<10;i++){ if(i>2&&i%3==0){ break;} System.out.println(i); } System.out.println("结束");} //输出结果就是1,2,结束。
2. In the switch statement Jump to the end of switch;
eg: Xiao Ming ran second in the school sports meeting. What was the reward he got?
Java code
public static void main(String[] args){ int paiming i=2; switch(paiming){ case 1: System.out.println("冠军"); break; case 2: System.out.println("亚军"); break; case 3: System.out.println("季军"); break; default: System.out.println("什么都没有!!"); }} //输出的结果就是“亚军”;在判断排名之后就会直接执行case 对应的数值,在break跳出整个switch。
3. Define an alias for the for loop, and then use the break alias; it means jumping to the end of the specified outer loop.
eg: Output * when there are 5 characters in the line, the outer label will pop up;
public class ForLoop{ public static void main(String[] args){ outer:for(int i=0;i<5;i++){ for(int j=0;j<10;j++){ if(j==5) break outer; System.out.print("*"); } System.out.print("\r\n"); } } //输出:*****。break 别名 直接跳出别名的循环。
Return: End the entire function and jump to the end of the function
eg: Output an even number from 1 to 10, when it is greater than 5 is the end.
public class uuu { public static void main(String[] args){ for(int i=1;i<10;i++){ if(i%3==0){ System.out.println(i); } if(i>5){ return; } } } } //输出结果:2 4 6。当输出到6的时候判断到大于5就return结束了这个函数。
eg: Output numbers from 1 to 6, but 3 cannot be output.
public class one{ public static void main(String[] args){ for(int i=1;i<=6;i++){ if(i==3){ continue; } System.out.println(i); } } } // 输出的结果:1,2,4,5,6.只有3不会输出,continue是结束当前次的循环。