switch statement in java

Switch statement

  • format

    switch (表达式) {
          
          
    	case 1:
    		语句体1;
    		break;
    	case 2:
    		语句体2;
    		break;
    	...
    	default:
    		语句体n+1;
    		break;
    }
    
  • Implementation process:

    • First calculate the value of the expression
    • Second, it is compared with case in turn. Once there is a corresponding value, the corresponding statement will be executed. During the execution, it will end when it encounters a break.
    • Finally, if all the cases do not match the value of the expression, the body of the default statement will be executed, and the program will end.
      For example:
      enter the number of weeks on the keyboard to display today’s weight loss activities
import java.util.Scanner;
public class C2{
    
    
	public static void main(String[] args){
    
    
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入星期数");
		int week = sc.nextInt();
		switch(week){
    
    
			case 1:
			       System.out.println("跑步");
				   break;
		    case 2:
			       System.out.println("游泳");
				   break;
			case 3:
			       System.out.println("慢走");
				   break;
		    case 4:
			       System.out.println("动感单车");
				   break;
			case 5:
			       System.out.println("拳击");
				   break;
		    case 6:
			       System.out.println("爬山");
				   break;
			case 7:
			       System.out.println("好好吃一顿");
				   break;
			default: 
				   System.out.println("您的输入有误");
				   break;	
		}
	}
}

switch statement case penetration

import java.util.Scanner;
public class C3{
    
    
	public static void main(String[] args){
    
    
		//case穿透 省略break语句,就会开始case穿透
		//当开始case穿透,后续的case就不会具有匹配效果,内部语句都会执行
		//直到看见break,或者将整体switch语句执行完毕,才会结束
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入星期数");
		int week = sc.nextInt();
		
		switch(week){
    
    
			
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			       System.out.println("工作日");
				   break;
			case 6:
			case 7:
			       System.out.println("休息日");
				   break;
		    default: 
				   System.out.println("您的输入有误");
				   break;	
		}
	}
}

Guess you like

Origin blog.csdn.net/qq_42073385/article/details/107721690