fork(1) download
  1. import java.util.*;
  2. import java.time.LocalDateTime;
  3. import java.time.format.DateTimeFormatter;
  4.  
  5. class Koyomi2 {
  6. static Scanner scanner = new Scanner(System.in);
  7. static int[] maxDays = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  8.  
  9. static int inputNumber(String message, int min, int max) {
  10. while(true) {
  11. System.out.print(message);
  12. String str = scanner.nextLine();
  13. System.out.println(str);
  14. try {
  15. int number = Integer.parseInt(str);
  16. if (min <= number && number <= max) {
  17. return number;
  18. }
  19. throw new NumberFormatException();
  20. } catch (NumberFormatException e) {
  21. System.out.println("正しい入力ではありません。");
  22. }
  23. }
  24. }
  25.  
  26. static boolean isLeap(int year) {
  27. return
  28. (year % 400 == 0) ? true :
  29. (year % 100 == 0) ? false :
  30. (year % 4 == 0) ? true : false;
  31. }
  32.  
  33. static int getLastDay(int year, int month) {
  34. return (month == 2 && isLeap(year)) ? 29 : maxDays[month - 1];
  35. }
  36.  
  37. static int getDayOfWeek(int year, int month, int day) {
  38. Calendar cal2 = Calendar.getInstance();
  39. cal2.set(Calendar.YEAR, year);
  40. cal2.set(Calendar.MONTH, month - 1);
  41. cal2.set(Calendar.DAY_OF_MONTH, day);
  42. return cal2.get(Calendar.DAY_OF_WEEK);
  43. }
  44.  
  45. public static void main(String[] args) {
  46. LocalDateTime now = LocalDateTime.now();
  47. System.out.println(now.format(DateTimeFormatter.ofPattern("今日はyyyy年MM月dd日です。")));
  48.  
  49. int year = inputNumber("何年のカレンダーを見ますか?2000~2040までの数字を入力して下さい。> ", 2000, 2040);
  50. int month = inputNumber("何月のカレンダーを見ますか?1~12までの数字を入力して下さい。> ", 1, 12);
  51.  
  52. System.out.println(String.format(" %d年 %d月", year, month));
  53. System.out.println("日 月 火 水 木 金 土");
  54. int youbi = getDayOfWeek(year, month, 1) - 1;
  55. System.out.print(String.format("%-" + (youbi * 3) + "s", ""));
  56. int lastDay = getLastDay(year, month);
  57. for (int day = 1; day <= lastDay; day++) {
  58. System.out.print(String.format("%2d ", day));
  59. if (getDayOfWeek(year, month, day) == Calendar.SATURDAY) {
  60. System.out.println("");
  61. }
  62. }
  63. System.out.println("");
  64. }
  65. }
  66.  
Success #stdin #stdout 0.26s 36428KB
stdin
0
-1
a
null
2016
2

stdout
今日は2018年06月12日です。
何年のカレンダーを見ますか?2000~2040までの数字を入力して下さい。> 0
正しい入力ではありません。
何年のカレンダーを見ますか?2000~2040までの数字を入力して下さい。> -1
正しい入力ではありません。
何年のカレンダーを見ますか?2000~2040までの数字を入力して下さい。> a
正しい入力ではありません。
何年のカレンダーを見ますか?2000~2040までの数字を入力して下さい。> null
正しい入力ではありません。
何年のカレンダーを見ますか?2000~2040までの数字を入力して下さい。> 2016
何月のカレンダーを見ますか?1~12までの数字を入力して下さい。> 2
     2016年 2月
日 月 火 水 木 金 土
    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