需求:輸入年、月,打印該月日曆。
public class CalendarPrinter {
// 判斷閏年
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
// 獲取月份天數
public static int getMonthDays(int year, int month) {
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
case 4: case 6: case 9: case 11: return 30;
case 2: return isLeapYear(year) ? 29 : 28;
default: return 0;
}
}
// 計算 1970-01-01 到目標年月 1 號的總天數
public static int getTotalDays(int year, int month) {
int days = 0;
// 年天數
for (int y = 1970; y < year; y++) {
days += isLeapYear(y) ? 366 : 365;
}
// 月天數
for (int m = 1; m < month; m++) {
days += getMonthDays(year, m);
}
return days;
}
// 打印日曆標題
public static void printTitle(int year, int month) {
System.out.println(year + "年" + month + "月");
System.out.println("日 一 二 三 四 五 六");
}
// 打印日曆主體
public static void printBody(int year, int month) {
int totalDays = getTotalDays(year, month);
int weekDay = (totalDays + 4) % 7; // 1號星期幾
int monthDays = getMonthDays(year, month);
// 打印 1 號前的空格
for (int i = 0; i < weekDay; i++) {
System.out.print(" ");
}
// 打印日期
for (int day = 1; day <= monthDays; day++) {
System.out.printf("%2d ", day);
if ((weekDay + day) % 7 == 0) System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
printTitle(2024, 1);
printBody(2024, 1);
}
}
雖然上例主要用循環計算,但陣列可優化月份天數查找:
// 陣列優化:索引 1-12 對應月份天數(非閏年)
static final int[] MONTH_DAYS = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static int getMonthDaysArray(int year, int month) {
if (month == 2 && isLeapYear(year)) return 29;
return MONTH_DAYS[month];
}
| 語法 | 說明 | 範例 |
|---|---|---|
| 類型[] 變數名 | 推薦風格 | int[] arr; |
| 類型 變數名[] | C 風格,不推薦 | int arr[]; |
| new 類型[長度] | 動態分配,默認值初始化 | new int[5] |
| {值1, 值2...} | 靜態初始化 | {1,2,3} |
| new 類型[]{值...} | 匿名陣列 | new int[]{1,2,3} |
ArrayListArrayIndexOutOfBoundsException