java select statement

Select statement --switch
switch statement format`

switch(表达式) {
case 常量值1:
语句体1;
 break;
 case 常量值2:
  语句体2;
  break; 
  ... 
  default: 
  语句体n+1; 
  break;

Execution flow
First, the value of the expression is calculated.
Second, it is compared with the case in turn. Once there is a corresponding value, the corresponding statement will be executed. In the process of execution, it will end when it encounters a break.
Finally, if all cases do not match the value of the expression, the body of the default statement will be executed, and then the program ends.
Insert picture description here

public static void main(String[] args) { 
//定义变量,判断是星期几 
int weekday = 6;
 //switch语句实现选择 
 switch(weekday) { 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; } 
        }

Case penetrability
In the switch statement, if break is not written after the case, there will be a penetrating phenomenon, that is, it will not judge the value of the next case, and run backwards directly until it encounters a break, or the overall switch ends .

public static void main(String[] args) { 
int i = 5; switch (i){ case 0: 
System.out.println("执行case0");
break; 
case 5: 
System.out.println("执行case5"); 
case 10: 
System.out.println("执行case10"); 
default: 
System.out.println("执行default");
 } 
}

In the above program, after executing case5, because there is no break statement, the program will always go backwards, and will not judge the case or break, and directly run the complete switch.
Due to the penetrability of case, beginners must write break when writing switch statements.

Published 28 original articles · Like1 · Visits1712

Guess you like

Origin blog.csdn.net/qq_45870494/article/details/103330599