Home  >  Article  >  Java  >  The use of jump statements in java

The use of jump statements in java

巴扎黑
巴扎黑Original
2016-12-10 09:41:411917browse

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;

Java code

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.

Java code

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结束了这个函数。

Continue: End the current loop and jump to the next loop

eg: Output numbers from 1 to 6, but 3 cannot be output.

Java code

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是结束当前次的循环。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn