1 import java.util.Scanner; 2 3 //D:\Program Files (x86)\eclipse\dropins 4 5 public class PerpetualCalendar { 6 7 static int year; //年 8 static int month; //月 9 10 static Scanner input = new Scanner(System.in); 11 12 public static void main(String[] args){ 13 14 int space; 15 16 InputYear(); 17 InputMonth(); 18 printTitle(year,month); 19 space = Week() - 1; 20 for(int i = 0; i < space; i++){ 21 22 System.out.print("\t"); 23 } 24 for(int j = 1; j <= Day(month); j++){ 25 26 System.out.print(j + "\t"); 27 if((j + space) % 7 == 0){ 28 29 System.out.println(); 30 } 31 } 32 33 34 } 35 //打印表頭 36 public static void printTitle(int year,int month){ 37 38 System.out.println(year + "年" + month + "月"); 39 System.out.println("-----------------------------------------------------"); 40 System.out.print("星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t星期日\t"); 41 System.out.println(); 42 } 43 //年份輸入 44 public static void InputYear(){ 45 46 do{ 47 System.out.println("請輸入年份:"); 48 year = input.nextInt(); 49 50 if(year < 1990){ 51 52 System.out.println("輸入年份錯誤:"); 53 } 54 }while(year < 1990); 55 } 56 //月份輸入 57 public static void InputMonth(){ 58 59 do{ 60 System.out.println("請輸入月份:"); 61 month = input.nextInt(); 62 63 if(month > 12 || month < 1){ 64 65 System.out.println("輸入月份錯誤:"); 66 } 67 }while(month > 12 || month < 1); 68 } 69 //計算天數 70 public static int CountDays(int year,int month){ 71 72 int days = 0; //日 73 for(int i = 1990; i < year; i++){ 74 75 if(IsLeapyear(i)){ 76 77 days = days + 366; 78 }else{ 79 80 days = days + 365; 81 } 82 } 83 84 //days加1進入下一年的1月1日 85 days++; 86 87 for(int j = 0; j < month ; j++){ 88 89 switch(j){ 90 91 case 1: 92 case 3: 93 case 5: 94 case 7: 95 case 8: 96 case 10: 97 case 12: 98 99 days = days + 31; 100 break; 101 case 4: 102 case 6: 103 case 9: 104 case 11: 105 106 days = days + 30; 107 break; 108 default: 109 if(IsLeapyear(year)){ 110 111 days = days + 29; 112 }else{ 113 114 days = days + 28; 115 } 116 } 117 } 118 return days; 119 } 120 //計算月初一號是星期幾 121 public static int Week(){ 122 123 int week = CountDays(year,month) % 7; 124 125 if(week == 0){ 126 127 week = 7; 128 } 129 130 return week; 131 } 132 //判斷本月是多少天 133 public static int Day(int month){ 134 135 int day; 136 switch(month){ 137 138 case 1: 139 case 3: 140 case 5: 141 case 7: 142 case 8: 143 case 10: 144 case 12: 145 146 day = 31; 147 break; 148 case 4: 149 case 6: 150 case 9: 151 case 11: 152 153 day = 30; 154 break; 155 default: 156 if(IsLeapyear(year)){ 157 158 day = 29; 159 }else{ 160 161 day = 28; 162 } 163 } 164 return day; 165 } 166 //計算平年還是閏年 返回值為布爾類型 167 public static boolean IsLeapyear(int year){ 168 169 return ((year % 4 == 0 && year % 100 != 0)||(year % 400 == 0)); 170 } 171 }
初學小白調的代碼,可能有很多BUG希望大神不吝賜教!!非常感謝!!
初學小白,望大神不吝賜教!