Home>Article> What is the format of switch statement?

What is the format of switch statement?

coldplay.xixi
coldplay.xixi Original
2020-12-22 11:15:22 29391browse

The switch statement format is [switch (expression) {case value 1: statement body 1; break; case value 2: statement body 2; break;]; where break means interrupt, and all values are When there is no match, the statement body default is executed.

What is the format of switch statement?

The switch statement format is:

1. The switch statement format is:

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

2. Format explanation:

Expression: byte, short, int, char

  • The value after case: just use To match the value of the expression

  • break: The meaning of table interruption

  • default: When all values do not match , Perform the statement default;

## 3. The execution process:

A: First calculate the value of the expression

B: Compare this calculated value with the value after the case in turn. Once there is a match, execute the corresponding statement and end when encountering break.

C: If all cases are not matched, execute the statement n 1

## 4. Example code:

Scanner sc= new Scanner(System.in); System.out.println("请输入数字1-7"); int i = sc.nextInt(); switch(i) { 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("星期天1");          break;         default:          System.out.println("请输入正确数字:");           break;

## related free Learning recommendations:
Programming Video

The above is the detailed content of What is the format of switch statement?. For more information, please follow other related articles on the PHP Chinese website!

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