1 import java.util.*; 2 public class Year{ 3 public static void main(String[] args){ 4 System.out.println("輸入年份和月份,判斷是否為閏年,並輸出當前月份的天數"); 5 System.out.println("請輸入你想要測試的年份:"); 6 Scanner in=new Scanner(System.in); 7 int year=in.nextInt(); 8 boolean bool=true; 9 int sum=0;//定義一個變量用來表示輸入的時間距離1900年有多少天 10 int k=0;//用來表示輸入的月份有幾天 11 while(bool){ 12 if(year<1900){ 13 System.out.println("計算機時間從1900年才開始,所以輸入有誤,請重新輸入:"); 14 year=in.nextInt(); 15 }else{ 16 bool=false; 17 } 18 } 19 if(year%4==0&&year%100!=0||year%400==0){ 20 System.out.println(year+"為閏年"); 21 }else{ 22 System.out.println(year+"為平年"); 23 } 24 System.out.println("請輸入你想要測試的月份:"); 25 int month=in.nextInt(); 26 bool=true; 27 while(bool){ 28 if(month>12||month<1){ 29 System.out.println("你輸入的月份不正確請重新輸入:"); 30 month=in.nextInt(); 31 }else{ 32 bool=false; 33 } 34 } 35 if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){ 36 System.out.println(month+"月有31天"); 37 }else if(year%4==0&&year%100!=0||year%400==0&&month==2){ 38 System.out.println(month+"月有29天"); 39 }else if(year%4!=0&&month==2){ 40 System.out.println(month+"月有28天"); 41 }else{ 42 System.out.println(month+"月有30天"); 43 } 44 for(int i=1;i<=month-1;i++){//求輸入的月份之前有多少天,eg:輸入5月求出1-4有幾天 45 if(i==2){ 46 if(year%4==0&&year%100!=0||year%400==0){ 47 sum=sum+29; 48 }else{ 49 sum=sum+28; 50 } 51 }else{ 52 if(i==4||i==6||i==9||i==11){ 53 sum=sum+30; 54 }else{ 55 sum=sum+31; 56 } 57 } 58 } 59 System.out.println(sum); 60 for(int i=1900;i<=year-1;i++){//求輸入的年份到1900年有多少天 61 if(i%4==0&&i%100!=0||i%400==0){ 62 sum=sum+366; 63 }else{ 64 sum=sum+365; 65 } 66 } 67 sum=sum+1;//輸入的日期距離1900年有多少天,+1是正好到了這一天 68 System.out.println(sum); 69 int weekday=sum%7;//算出到1900年有多少星期 70 System.out.println("當月日歷如下:"); 71 System.out.println(year+"年"+month+"月的日歷"); 72 System.out.println("日\t一\t二\t三\t四\t五\t六"); 73 for(int i=1;i<=weekday;i++){ 74 System.out.print("\t"); 75 }//輸入月份第一天是周幾 76 if(month==2){ 77 if(year%4==0&&year%100!=0||year%400==0){ 78 k=29; 79 }else{ 80 k=28; 81 } 82 }else{ 83 if(month==4||month==6||month==9||month==11){ 84 k=30; 85 }else{ 86 k=31; 87 } 88 }//輸入的月有幾天 89 for(int i=1;i<=k;i++){ 90 if(sum%7==6){ 91 System.out.print(i+"\n"); 92 }else{ 93 System.out.print(i+"\t"); 94 } 95 sum++; 96 }//輸出打印日歷 97 98 } 99 }