我有一个I类课程,我必须制作一个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(星期二)等)
现在,我可以使用非常混乱的switch语句和嵌套的if语句,根据Day的值和当月的天数,打印出这个预制日历,我可以预先 - 为日期和该月份的天数的每个最终组合制作日历。但我不想这样做,我无法找到一种更简单的方法。有没有人有任何更简洁,更简洁的方法呢?它会涉及二维阵列吗?
PS。我不允许使用Java中提供的任何基于日期的库类。
答案 0 :(得分:0)
如果你改变主意,你可以使用它
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(" ");
}}}