輸入年份與月份,控制台打印該月份的日曆表,格式如:
2017年 1月
日 一 二 三 四 五 六
1 2 3 4 5 6 7
8 9 10 11 12 13 14
...
switch 判斷月份,2 月結合閏年規則。isLeapYear(year):判斷閏年獨立方法。getTotalDays(year, month):計算距 1970-01-01 總天數。getMonthDays(year, month):返回當月天數。printTitle(year, month):打印年月表頭。printBody(firstWeekDay, monthDays):打印日期主體。main():接收輸入,串聯調用。// 判斷閏年
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
// 計算 1 日星期幾(0=周日)
public static int getFirstWeekDay(int year, int month) {
int totalDays = 0;
for (int y = 1970; y < year; y++) totalDays += isLeapYear(y) ? 366 : 365;
for (int m = 1; m < month; m++) totalDays += getMonthDays(year, m);
return (totalDays + 4) % 7; // 1970-01-01 是周四(4)
}
「自頂向下分析,自底向上實現」:將大問題拆解為閏年判斷、天數累加、星期計算、格式打印等獨立小模塊,逐個擊破,最後組裝。這是處理邏輯類問題的通用思維,亦是良好編程習慣的體現。