1. 程式人生 > >用java實現列印任一年的日曆

用java實現列印任一年的日曆

Code:
  1. import java.io.BufferedReader;   
  2. import java.io.IOException;   
  3. import java.io.InputStreamReader;   
  4. publicclass TextControl {   
  5. staticint year,monthDay,weekDay;  //定義靜態變數,以便其它類呼叫
  6. publicstaticvoid main(String[] args) throws IOException   
  7.      {   
  8.       System.out.print(
    "請輸入一個年份:");   
  9.       InputStreamReader ir;  //以下6行程式碼接受從控制檯輸入
  10.       BufferedReader in;   
  11.       ir=new InputStreamReader(System.in);   
  12.       in=new BufferedReader(ir);   
  13.       String s=in.readLine();   
  14.       year=Integer.parseInt(s);   
  15.       weekDay=firstDay(year);  //計算該年第一天是星期幾
  16.       System.out.println("/n          "+year+"年          ");   
  17.       printMonth();   
  18.      }   
  19. publicstaticboolean isLeapYear(int y)  //叛別是否是閏年
  20.      {   
  21. return ((y%4==0 && y%100!=0) || (y%400==0));   
  22.      }   
  23. publicstaticint firstDay(int y)  //計算該年第一天是星期幾
  24.      {   
  25. long n=y*365;   
  26. for(int i=1;i<y;i++)   
  27. if(isLeapYear(i))   
  28.         n+=1;    
  29. return (int)n%7;   
  30.      }   
  31. publicstaticvoid printWeek()  //列印標頭
  32.      {   
  33.       System.out.println("===========================");   
  34.       System.out.println("日  一  二  三  四  五  六");   
  35.      }   
  36. publicstaticint getMonthDay(int m)  //獲取每個月的天數
  37.      {   
  38. switch(m)   
  39.       {   
  40. case1:   
  41. case3:   
  42. case5:   
  43. case7:   
  44. case8:   
  45. case10:   
  46. case12return31;   
  47. case4:   
  48. case6:   
  49. case9:   
  50. case11return30;   
  51. case2:   
  52. if(isLeapYear(year)) return29;   
  53. elsereturn28;   
  54. defaultreturn0;   
  55.       }   
  56.      }   
  57. publicstaticvoid printMonth()  //分別按不同條件逐月列印
  58.      {   
  59. for(int m=1;m<=12;m++)    //迴圈
  60.       {   
  61.        System.out.println(m+"月");    
  62.        printWeek();   
  63. for(int j=1;j<=weekDay;j++)  //按每個月第一天是星期幾列印相應的空格
  64.          System.out.print("    ");   
  65. int monthDay=getMonthDay(m);  //獲取每個月的天數
  66. for(int d=1;d<=monthDay;d++)     
  67.        {   
  68. if(d<10)                                  //以下4行對輸出格式化
  69.          System.out.print(d+"   ");   
  70. else
  71.          System.out.print(d+"  ");   
  72.         weekDay=(weekDay+1)%7;   //每列印一天後,反應第二天是星期幾
  73. if(weekDay==0)  //如果第二天是星期天,便換行。
  74.          System.out.println();   
  75.        }   
  76.        System.out.println('/n');   
  77.       }   
  78.      }  

這個程式是在某本書上看到的,但是中間一個方法不太清除,下面這段:

Code:
  1. publicstaticint firstDay(int y)  //計算該年第一天是星期幾
  2.  {   
  3. long n=y*365;   
  4. for(int i=1;i<y;i++)   
  5. if(isLeapYear(i))   
  6.     n+=1;    
  7. return (int)n%7;   
  8.  }  

請知道的同學,老師給予指點,不勝感激