java写中国的2023年的日历用一维数组注释用中文要求我输入的是几月就打印几月的日历
以下是一个使用一维数组实现打印中国2023年日历的Java代码,根据输入的月份打印相应的月份日历:
import java.util.Scanner;
public class Calendar2023 {
public static void main(String[] args) {
// 定义每个月的天数
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 定义每个月的名称
String[] monthNames = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"};
// 获取用户输入的月份
Scanner scanner = new Scanner(System.in);
System.out.print("请输入月份(1-12):");
int month = scanner.nextInt();
if (month < 1 || month > 12) {
System.out.println("输入的月份无效!");
return;
}
// 获取该月份的天数
int days = daysInMonth[month - 1];
// 打印日历标题
System.out.println("中国2023年" + monthNames[month - 1] + "日历");
// 打印日历表头
System.out.println("日\t一\t二\t三\t四\t五\t六");
// 计算该月份1号是星期几
int weekdayOfFirstDay = calculateWeekday(2023, month, 1);
// 打印日历的第一行缩进
for (int i = 0; i < weekdayOfFirstDay; i++) {
System.out.print("\t");
}
// 打印日历的日期
for (int i = 1; i <= days; i++) {
System.out.print(i + "\t");
if ((i + weekdayOfFirstDay) % 7 == 0) {
System.out.println();
}
}
}
// 计算某年某月某日是星期几,使用Zeller公式
private static int calculateWeekday(int year, int month, int day) {
if (month < 3) {
month += 12;
year--;
}
int century = year / 100;
year %= 100;
int weekday = (year + year / 4 + century / 4 - 2 * century + 26 * (month + 1) / 10 + day - 1) % 7;
if (weekday < 0) {
weekday += 7;
}
return weekday;
}
}
此代码中,我们首先定义了每个月的天数和月份名称的一维数组。然后,通过Scanner类获取用户输入的月份,判断输入是否有效。
接下来,我们使用calculateWeekday函数计算了该月份1号是星期几。然后,通过循环打印日历的表头和日期,其中日期打印时根据每行7个日期进行换行处理。
请注意,此代码还使用了Zeller公式来计算某年某月某日是星期几。这是一个常用的计算公式,可在代码中使用,以便准确计算星期几
原文地址: https://www.cveoy.top/t/topic/ihRI 著作权归作者所有。请勿转载和采集!