編寫一個控制台程序,接收用戶輸入的年份與月份,輸出該月的日曆表,正確顯示每月天數、起始星期及閏年判斷。
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)(totalDays + 1) % 7,0 代表周日import java.util.Scanner;
public class PrintCalendar {
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();
System.out.println("\n*********" + year + "年" + month + "月 日曆表************");
// 閏年判斷
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
// 累計 1900 年至輸入年份前的總天數
int totalDays = 0;
for (int y = 1900; y < year; y++) {
totalDays += ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) ? 366 : 365;
}
// 累計當年 1 月至上個月的天數
int[] monthDays = {31, isLeap?29:28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for (int m = 0; m < month - 1; m++) totalDays += monthDays[m];
// 計算月初星期
int firstDay = (totalDays + 1) % 7; // 0=Sun, 1=Mon...
// 輸出表頭
System.out.println("周日\t周一\t周二\t周三\t周四\t周五\t周六");
// 輸出前導空格
for (int i = 0; i < firstDay; i++) System.out.print("\t");
// 輸出日期
for (int d = 1; d <= monthDays[month-1]; d++) {
System.out.print(d + "\t");
if ((firstDay + d) % 7 == 0) System.out.println();
}
}
}
請輸入年份:2024 請輸入月份:5 *********2024年5月 日曆表************ 周日 周一 周二 周三 周四 周五 周六 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31