????????????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 firstDayOfWeek = getFirstDayOfWeek(year, month); // ???? System.out.println(" ? ? ? ? ? ? ?"); // ???? for (int i = 0; i < firstDayOfWeek; i++) { System.out.print(" "); } // ???? int daysInMonth = getDaysInMonth(year, month); for (int i = 1; i <= daysInMonth; i++) { System.out.printf("= ", i); if ((i + firstDayOfWeek) % 7 == 0) { System.out.println(); } } } public static int getFirstDayOfWeek(int year, int month) { int totalDays = 0; // ???1900?1?1?????????? for (int i = 1900; i < year; i++) { totalDays += isLeapYear(i) ? 366 : 365; } for (int i = 1; i < month; i++) { totalDays += getDaysInMonth(year, i); } // ?????????????? return (totalDays + 1) % 7; } public static boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } public static int getDaysInMonth(int year, int month) { if (month == 2) { return isLeapYear(year) ? 29 : 28; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else { return 31; } } }
?????,??????????,?????????????
??:?????????????,???????????????,???2???29?,???2???28??