switch case使用
时间: 2024-04-12 20:26:17 浏览: 90
switch case是一种在编程中常用的条件语句,它可以根据不同的条件值执行不同的代码块。通常用于多个条件判断时,可以提高代码的可读性和执行效率。
switch case语句的基本语法如下:
```
switch (expression) {
case value1:
// 当expression的值等于value1时执行的代码块
break;
case value2:
// 当expression的值等于value2时执行的代码块
break;
...
default:
// 当expression的值与前面的case都不匹配时执行的代码块
break;
}
```
在switch后面的括号中,我们需要提供一个表达式(expression),它的值会与每个case后面的值进行比较。当expression的值与某个case后面的值相等时,就会执行对应的代码块。如果没有匹配的case,那么会执行default后面的代码块。
需要注意的是,在每个case后面都需要使用`break`语句来结束当前的代码块,否则会继续执行下一个case中的代码。如果不想使用`break`语句,可以让多个case共享同一个代码块。
以下是一个使用switch case语句的示例:
```
int num = 2;
switch (num) {
case 1:
System.out.println("数字是1");
break;
case 2:
System.out.println("数字是2");
break;
case 3:
System.out.println("数字是3");
break;
default:
System.out.println("数字不在1、2、3之间");
break;
}
```
以上代码中,根据num的值,会输出"数字是2"。
阅读全文
相关推荐















