Java用switch语句来实现判断今天是星期几。
时间: 2024-10-13 15:11:54 浏览: 96
在Java中,你可以使用`switch`语句配合`DayOfWeek`枚举来判断今天是星期几。首先,你需要导入`java.time.DayOfWeek`类,然后定义一个变量存储当前日期的星期,比如`LocalDate`对象的`getDayOfWeek()`方法返回的就是`DayOfWeek`枚举值。下面是一个示例:
```java
import java.time.LocalDate;
import java.time.temporal.Weekday;
public class Main {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now(); // 获取当前日期
Weekday dayOfWeek = currentDate.getDayOfWeek(); // 获取星期
switch (dayOfWeek) {
case MONDAY:
System.out.println("今天是周一");
break;
case TUESDAY:
System.out.println("今天是周二");
break;
case WEDNESDAY:
System.out.println("今天是周三");
break;
case THURSDAY:
System.out.println("今天是周四");
break;
case FRIDAY:
System.out.println("今天是周五");
break;
case SATURDAY:
System.out.println("今天是周六");
break;
case SUNDAY:
System.out.println("今天是周日");
break;
default:
throw new IllegalArgumentException("非法的星期");
}
}
}
```
阅读全文