1. 程式人生 > >java初學乍練之用Calendar列印萬年曆

java初學乍練之用Calendar列印萬年曆

題目:

列印萬年曆,如:

                2018年 4月  日曆
日      一      二      三      四      五      六
 1       2       3       4       5       6       7
 8       9      10      11      12      13      14
15      16      17      18      19      20      21
22      23      24      25      26      27      28

29      30

思路:

Calendar中有很多時間屬性, 合理的呼叫他們可以讓列印日曆更簡單.

程式碼:

import java.util.*;
class PerpetialCalendar{
	public static void main(String[] args)throws Exception{
		Scanner sc1 = new Scanner(System.in);
		Scanner sc2 = new Scanner(System.in);
		Calendar c = Calendar.getInstance();
		System.out.println("請輸入年份:");
		int y = c.get(Calendar.YEAR);
		try{
			y = sc1.nextInt();//鍵盤輸入如果不是數字則會出現異常
		}catch(Exception ey){
			y = c.get(Calendar.YEAR);//出現異常則列印本年日曆
			System.out.println("年份輸入異常!將列印"+y+"年的日曆");
		}
		System.out.println("請輸入月份:");
		int m = 1;
		try{
			m = sc2.nextInt()-1;//兩個Scanner物件可將年份異常和月份異常分開對待
			if (m<0 || m>11) throw new Exception();//如果月份輸入其他數字,也丟擲異常
		}catch(Exception ep){
			m = c.get(Calendar.MONTH);//出現異常則列印本月日曆
			System.out.println("月份輸入異常!將列印"+(m+1)+"月的日曆");
		}
		c.set(y, m, 1);//設定需列印的日曆
		System.out.println(String.format("\t\t%d年 %d月  日曆", y, m+1));//日曆標題
		System.out.println("日\t一\t二\t三\t四\t五\t六");//列印日曆頭
		for(int i=0; i<c.get(Calendar.DAY_OF_WEEK)-1; i++){//列印每月1號前的空格,
			System.out.print("\t");
		}
		do{
			System.out.print(String.format("%2d\t", c.get(Calendar.DAY_OF_MONTH)));//列印日期,打一個跳個table
			c.add(Calendar.DAY_OF_MONTH, 1);		//列印一天, 加一天
			if(c.get(Calendar.DAY_OF_WEEK)==1){		//遇到星期天就換行
				System.out.println();
			}	
		}while(c.get(Calendar.DAY_OF_MONTH)!=1);	//當日期重新變回1號的時候,停止列印,
	}
	
}