java中switch用法
时间: 2024-03-23 21:34:47 浏览: 195
Java中Switch用法代码示例
5星 · 资源好评率100%
以下是Java中switch用法的两个例子:
1. 使用整型变量作为switch的表达式[^1]:
```java
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("Day: " + dayName); // 输出:Wednesday
```
2. 使用字符串变量作为switch的表达式[^2]:
```java
String seasonName = "summer";
String seasonType;
switch (seasonName) {
case "spring":
seasonType = "Warm";
break;
case "summer":
seasonType = "Hot";
break;
case "autumn":
seasonType = "Cool";
break;
case "winter":
seasonType = "Cold";
break;
default:
seasonType = "Invalid season";
break;
}
System.out.println("Season type: " + seasonType); // 输出:Hot
```
阅读全文