java d case when
时间: 2024-12-27 08:18:32 浏览: 1
### Java 中 `switch` 语句的用法
在 Java 编程语言中,`switch` 语句提供了一种基于表达式的多路分支机制。下面是一个简单的例子展示如何使用 `switch` 来处理不同情况:
```java
public class DayOfWeek {
public static String getDayName(int dayNumber) {
String dayName;
switch (dayNumber) {
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 number";
}
return dayName;
}
public static void main(String[] args) {
int today = 3; // Wednesday
System.out.println("Today is " + getDayName(today));
}
}
```
在这个例子中,程序会根据传入的整数参数决定一周中的哪一天,并返回相应的字符串表示形式。
需要注意的是,在较新的 Java 版本(自 JDK 12 开始),引入了增强型 `switch` 表达式语法[^1],它允许更简洁地编写相同的逻辑而不需要显式声明变量并使用 `break` 关键字:
```java
public class EnhancedSwitchExample {
public static String getMonthNameEnhanced(int monthNumber) {
return switch (monthNumber) {
case 1 -> "January";
case 2 -> "February";
case 3 -> "March";
case 4 -> "April";
case 5 -> "May";
case 6 -> "June";
case 7 -> "July";
case 8 -> "August";
case 9 -> "September";
case 10 -> "October";
case 11 -> "November";
case 12 -> "December";
default -> "Invalid Month Number";
};
}
public static void main(String[] args) {
int currentMonth = 5; // May
System.out.println("Current month is " + getMonthNameEnhanced(currentMonth));
}
}
```
此版本利用箭头 (`->`) 将条件映射到结果值,从而简化代码结构和可读性。
阅读全文