如何在控制台中打印日历月份?

问题描述:

我有一个任务需要创建一个Java控制台应用程序,它涉及到要求用户输入日期,解析该日期以及确定该日期从哪一天开始。我必须再打印出的日历,看起来像这样:如何在控制台中打印日历月份?

Calendar for September 2016 
Su Mo Tu We Th Fr Sa 
- - - - 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 - 

我有约会,我有一天数的日期开始日(如天= 1(星期一),天= 2(星期二)等)

现在,我可以使用一个非常凌乱的外观if语句的嵌套if语句,根据Day的值和当月天数打印出这个pre自制的日历,我可以预先为每个日期和当月的天数组合预先制作一个日历。但我不想那样做,我也找不到一个更简单的方法。有没有人有过更简洁,更简洁的方法?会涉及二维数组吗?

PS。我不被允许使用Java中的任何基于日期的库类。

+0

使用“我不允许使用在Java中使用任何基于日期的库类。”那么你如何制定给定月份的开始日期? –

+0

如何在没有日期库的情况下知道当月的哪一天开始? –

+0

没有内置的java类,没有更简单的方法。你如何看待它在内置的java类中实现?你必须使用你的杂乱开关和if语句。此外,你应该保留一个方法来检查闰年 – rafid059

好,你可以,如果你改变主意

public static void main(String args []) 
    { 

     // type MM yyyy 
     Scanner in = new Scanner(System.in); 
     System.out.print("Enter month and year: MM yyyy "); 
     int month = in.nextInt(); 
     int year = in.nextInt(); 
     in.close(); 
     // checks valid month 
     try { 

      if (month < 1 || month > 12) 
       throw new Exception("Invalid index for month: " + month); 
      printCalendarMonthYear(month, year);} 

     catch (Exception e) { 
      System.err.println(e.getMessage()); 
     } 
    } 

    private static void printCalendarMonthYear(int month, int year) { 
     Calendar cal = new GregorianCalendar(); 
     cal.clear(); 
     cal.set(year, month - 1, 1); // setting the calendar to the month and year provided as parameters 
     System.out.println("Calendar for "+ cal.getDisplayName(Calendar.MONTH, Calendar.LONG, 
         Locale.US) + " " + cal.get(Calendar.YEAR));//to print Calendar for month and year 
     int firstWeekdayOfMonth = cal.get(Calendar.DAY_OF_WEEK);//which weekday was the first in month 
     int numberOfMonthDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH); //lengh of days in a month 
     printCalendar(numberOfMonthDays, firstWeekdayOfMonth); 
    } 
    private static void printCalendar(int numberOfMonthDays, int firstWeekdayOfMonth) { 
     int weekdayIndex = 0; 
     System.out.println("Su MO Tu We Th Fr Sa"); // The order of days depends on your calendar 

     for (int day = 1; day < firstWeekdayOfMonth; day++) { 
      System.out.print(" "); //this loop to print the first day in his correct place 
      weekdayIndex++; 
     } 
     for (int day = 1; day <= numberOfMonthDays; day++) { 

      if (day<10) // this is just for better visialising because unit number take less space of course than 2 
      System.out.print(day+" "); 
      else System.out.print(day); 
      weekdayIndex++; 
      if (weekdayIndex == 7) { 
       weekdayIndex = 0; 
       System.out.println(); 
      } else { 
       System.out.print(" "); 
      }}} 
+2

请解释你的答案。否则,这对该网站的未来访问者不利。所有你会做的是勺喂养OP,并剥夺他创建自己的代码的好处。 –

+0

OP不允许使用任何内置的基于日期的类。然而你在你的答案中使用了'GregorianCalendar' – rafid059