JAVA编程实现输入一个年份,控制台输出年历
时间: 2023-10-17 09:29:21 浏览: 126
好的,我可以帮你实现这个功能。以下是一个简单的Java程序,可以输入一个年份,然后输出该年份的年历。
```java
import java.util.Scanner;
public class YearCalendar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份:");
int year = scanner.nextInt();
// 计算每个月的天数
int[] daysInMonth = new int[12];
for (int i = 0; i < 12; i++) {
if (i == 1) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
daysInMonth[i] = 29;
} else {
daysInMonth[i] = 28;
}
} else if (i == 3 || i == 5 || i == 8 || i == 10) {
daysInMonth[i] = 30;
} else {
daysInMonth[i] = 31;
}
}
// 计算该年份的第一天是星期几
int firstDayOfYear = getFirstDayOfYear(year);
// 输出年历
System.out.println(year + "年");
System.out.println("一\t二\t三\t四\t五\t六\t日");
int dayOfWeek = firstDayOfYear;
for (int i = 0; i < 12; i++) {
for (int j = 0; j < dayOfWeek; j++) {
System.out.print("\t");
}
for (int j = 1; j <= daysInMonth[i]; j++) {
System.out.print(j + "\t");
dayOfWeek++;
if (dayOfWeek == 7) {
System.out.println();
dayOfWeek = 0;
}
}
System.out.println();
}
}
// 计算该年份的第一天是星期几
private static int getFirstDayOfYear(int year) {
int dayOfWeek = (year + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400) % 7;
return dayOfWeek == 0 ? 7 : dayOfWeek;
}
}
```
你可以将这个代码复制到你的IDE中运行,或者直接在控制台中运行该程序。运行程序后,输入一个年份,例如:2022,然后按回车键,程序就会输出该年份的年历。
阅读全文