用java實現列印任一年的日曆
阿新 • • 發佈:2018-12-25
Code:
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- publicclass TextControl {
- staticint year,monthDay,weekDay; //定義靜態變數,以便其它類呼叫
- publicstaticvoid main(String[] args) throws IOException
- {
- System.out.print(
- InputStreamReader ir; //以下6行程式碼接受從控制檯輸入
- BufferedReader in;
- ir=new InputStreamReader(System.in);
- in=new BufferedReader(ir);
- String s=in.readLine();
- year=Integer.parseInt(s);
- weekDay=firstDay(year); //計算該年第一天是星期幾
- System.out.println("/n "+year+"年 ");
- printMonth();
- }
- publicstaticboolean isLeapYear(int y) //叛別是否是閏年
- {
- return ((y%4==0 && y%100!=0) || (y%400==0));
- }
- publicstaticint firstDay(int y) //計算該年第一天是星期幾
- {
- long n=y*365;
- for(int i=1;i<y;i++)
- if(isLeapYear(i))
- n+=1;
- return (int)n%7;
- }
- publicstaticvoid printWeek() //列印標頭
- {
- System.out.println("===========================");
- System.out.println("日 一 二 三 四 五 六");
- }
- publicstaticint getMonthDay(int m) //獲取每個月的天數
- {
- switch(m)
- {
- case1:
- case3:
- case5:
- case7:
- case8:
- case10:
- case12: return31;
- case4:
- case6:
- case9:
- case11: return30;
- case2:
- if(isLeapYear(year)) return29;
- elsereturn28;
- default: return0;
- }
- }
- publicstaticvoid printMonth() //分別按不同條件逐月列印
- {
- for(int m=1;m<=12;m++) //迴圈
- {
- System.out.println(m+"月");
- printWeek();
- for(int j=1;j<=weekDay;j++) //按每個月第一天是星期幾列印相應的空格
- System.out.print(" ");
- int monthDay=getMonthDay(m); //獲取每個月的天數
- for(int d=1;d<=monthDay;d++)
- {
- if(d<10) //以下4行對輸出格式化
- System.out.print(d+" ");
- else
- System.out.print(d+" ");
- weekDay=(weekDay+1)%7; //每列印一天後,反應第二天是星期幾
- if(weekDay==0) //如果第二天是星期天,便換行。
- System.out.println();
- }
- System.out.println('/n');
- }
- }
這個程式是在某本書上看到的,但是中間一個方法不太清除,下面這段:
Code:- publicstaticint firstDay(int y) //計算該年第一天是星期幾
- {
- long n=y*365;
- for(int i=1;i<y;i++)
- if(isLeapYear(i))
- n+=1;
- return (int)n%7;
- }
請知道的同學,老師給予指點,不勝感激