用Java写一个万年历
时间: 2023-03-31 10:02:38 浏览: 139
用Java语言编写窗口万年历
3星 · 编辑精心推荐
好的,以下是用 Java 写一个万年历的代码:
import java.util.Scanner;
public class Calendar {
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();
printCalendar(year, month);
}
public static void printCalendar(int year, int month) {
int days = getDaysOfMonth(year, month);
int firstDayOfWeek = getFirstDayOfWeek(year, month);
System.out.println("日\t一\t二\t三\t四\t五\t六");
for (int i = ; i < firstDayOfWeek; i++) {
System.out.print("\t");
}
for (int i = 1; i <= days; i++) {
System.out.print(i + "\t");
if ((i + firstDayOfWeek) % 7 == ) {
System.out.println();
}
}
}
public static int getDaysOfMonth(int year, int month) {
int days = ;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
if (isLeapYear(year)) {
days = 29;
} else {
days = 28;
}
break;
}
return days;
}
public static boolean isLeapYear(int year) {
return (year % 4 == && year % 100 != ) || year % 400 == ;
}
public static int getFirstDayOfWeek(int year, int month) {
int dayOfWeek = ;
int totalDays = ;
for (int i = 190; i < year; i++) {
if (isLeapYear(i)) {
totalDays += 366;
} else {
totalDays += 365;
}
}
for (int i = 1; i < month; i++) {
totalDays += getDaysOfMonth(year, i);
}
dayOfWeek = (totalDays + 1) % 7;
return dayOfWeek;
}
}
希望能够帮到你!
阅读全文