java万年历
时间: 2023-10-11 18:19:35 浏览: 155
好的,我可以帮你写一个 Java 万年历程序。以下是代码示例:
```java
import java.util.Scanner;
public class Calendar {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入年份:");
int year = input.nextInt();
System.out.print("请输入月份:");
int month = input.nextInt();
// 计算这个月的天数
int days = getDaysOfMonth(year, month);
// 计算这个月的第一天是星期几
int firstDayOfWeek = getFirstDayOfWeek(year, month);
// 打印日历表头
System.out.println("日\t一\t二\t三\t四\t五\t六");
// 打印日历内容
int day = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
if (i == 0 && j < firstDayOfWeek) {
System.out.print("\t");
} else if (day > days) {
break;
} else {
System.out.print(day + "\t");
day++;
}
}
System.out.println();
}
}
// 获取指定年月的天数
public static int getDaysOfMonth(int year, int month) {
int days = 0;
switch (month) {
case 2:
if (isLeapYear(year)) {
days = 29;
} else {
days = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
days = 31;
break;
}
return days;
}
// 判断指定年份是否是闰年
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
// 获取指定年月的第一天是星期几
public static int getFirstDayOfWeek(int year, int month) {
int century = year / 100;
year = year % 100;
int dayOfWeek = (1 + 5 * (year % 4) + 4 * (year % 100) + 6 * (year % 400)) % 7;
if (century == 18) {
dayOfWeek += 2;
} else if (century == 20) {
dayOfWeek += 6;
}
switch (month) {
case 1:
break;
case 2:
dayOfWeek += 3;
break;
case 3:
dayOfWeek += 3;
break;
case 4:
dayOfWeek += 6;
break;
case 5:
dayOfWeek += 1;
break;
case 6:
dayOfWeek += 4;
break;
case 7:
dayOfWeek += 6;
break;
case 8:
dayOfWeek += 2;
break;
case 9:
dayOfWeek += 5;
break;
case 10:
dayOfWeek += 0;
break;
case 11:
dayOfWeek += 3;
break;
case 12:
dayOfWeek += 5;
break;
}
return dayOfWeek % 7;
}
}
```
你可以直接运行这个程序,输入年份和月份,即可输出对应的万年历。
阅读全文