本关任务:编写程序,实现以下功能: 输入一个日期(年月日),计算该日期是星期几。并输出日期和星期几。 例如: 输入:2022 3 24 输出:今天是2022 MARCH 24 THURSDAY
时间: 2024-03-26 11:41:22 浏览: 152
以下是一个实现题目要求的Java程序:
```java
import java.util.*;
public class WeekdayCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 获取输入的年月日
System.out.print("请输入年份: ");
int year = scanner.nextInt();
System.out.print("请输入月份: ");
int month = scanner.nextInt();
System.out.print("请输入日期: ");
int day = scanner.nextInt();
// 使用Calendar类计算星期几
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, day);
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
// 将星期几转换为字符串
String[] weekdays = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
String weekdayStr = weekdays[weekday - 1];
// 将月份转换为字符串
String[] months = {"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"};
String monthStr = months[month - 1];
// 输出结果
System.out.println("今天是" + year + " " + monthStr + " " + day + " " + weekdayStr);
}
}
```
该程序首先使用Scanner类获取用户输入的年月日,然后使用Calendar类计算该日期是星期几。最后,将年月日和星期几输出为字符串。运行程序,输入年月日后即可得到输出结果。
阅读全文