1、方法,需要一個年份,一個月份。然后在控制台輸出日歷
1 // 輸入一個年份和一個月份顯示日歷 2 public static void printCalendar(int year, int month) { 3 // 轉換日期 4 Calendar calendar = Calendar.getInstance(); 5 // 找到月份第一天 6 calendar.set(year, month-1, 1); 7 // 找到第一天是周幾 1 周日 2 周一 8 int week = calendar.get(Calendar.DAY_OF_WEEK); 9 //System.out.println("week: "+week); 10 // 獲取最大日期 11 int dayMax = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 12 // 循環輸出 13 System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t"); 14 // 若第一天不為周日 15 if(week != 1) { 16 // 判斷01是周幾 空格 17 for(int j = 1;j < week;j++) { 18 System.out.print(" \t"); 19 } 20 } 21 // 循環 22 for (int i = 1; i <= dayMax; i++) { 23 // 找到第 i 天 24 calendar.set(year, month-1, i); 25 // 第 i 天是周幾 26 int wek = calendar.get(Calendar.DAY_OF_WEEK); 27 System.out.print(i + "\t"); 28 // 周六回車 29 if ( wek == 7) { 30 System.out.println(); 31 } 32 33 } 34 }
2、MainTest測試類
1 public static void main(String[] args) { 2 // 萬年歷測試類 3 Scanner scanner = new Scanner(System.in); 4 boolean isTrue = true; 5 while(isTrue) { 6 System.out.println("-------------萬年歷------------"); 7 System.out.println("1、查看日歷"); 8 System.out.println("0、退出"); 9 int key = scanner.nextInt(); 10 switch (key) { 11 case 1: 12 System.out.println("請輸入年份:"); 13 int year = scanner.nextInt(); 14 System.out.println("請輸入月份:"); 15 int month = scanner.nextInt(); 16 PerpetualCalendar.printCalendar(year, month); 17 System.out.println(); 18 break; 19 default: 20 isTrue = false; 21 break; 22 } 23 } 24 System.out.println("已退出系統..."); 25 }
3、運行結果:
有幫助,就點個推薦吧,讓更多人看到