第5章 日付と時刻の新たな API : 問題 4 : カレンダー
問題
指定された月のカレンダーを表示するプログラムを書け
例えば java Cal 3 2013
を実行すると、次のように表示する
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 31
週は、月曜日から始まるものとする
解答
コマンドライン引数で指定される年月にピッタリのクラスYearMonth
がある
入力値はYearMonth
クラスで受ける
public class Cal { public static void main(String[] args) { // コマンドライン引数のチェックは省略 … RuntimeException で落ちる :-P YearMonth yearMonth = YearMonth.of( Integer.parseInt(args[1]), Integer.parseInt(args[0]) ); LocalDate day = yearMonth.atDay(1); LocalDate lastDay = yearMonth.atEndOfMonth(); // 先頭行のインデント int n = day.getDayOfWeek().getValue() - 1; for (int i = 0; i < n; i++) { System.out.print(" "); } // 日付を右寄せで while (day.isBefore(lastDay) || day.isEqual(lastDay)) { System.out.printf("%2d", day.getDayOfMonth()); // 1文字空ける or 改行 if (day.getDayOfWeek() == DayOfWeek.SUNDAY) { System.out.println(); } else { System.out.print(" "); } day = day.plusDays(1); } } }