0
我試圖打印出任何一年的全年日曆。代碼在正確的一天每個月開始,但是繼續計算出七位數並將下一行返回到同一起始列。我該如何解決這個問題?日曆打印機 - 如何返回每個新行
這裏是我的電流輸出:
2017
January
Sun Mon Tue Wed Thu Fri Sat
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
February
Sun Mon Tue Wed Thu Fri Sat
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
而且仍在繼續爲一年。我相信這個錯誤是在printCalendar方法中,但我不知道該怎麼做。 這裏是我的代碼:
import java.util.Scanner;
import java.io.*;
public class CalendarPrinter{
public static void main(String[]args)throws IOException{
Scanner kbd = new Scanner(System.in);
System.out.println("Calendar Printer\n");
System.out.print("Enter the year? ");
int year = kbd.nextInt();
printCalendar(year);
System.out.println("\n" + year + ".txt generated.");
}
public static void printCalendar(int year) throws IOException {
PrintWriter outputFile = new PrintWriter(year + ".txt");
outputFile.println(" " + year);
for(int month = 1; month <=12; month++) {
outputFile.println("\n " + getMonthName(month));
outputFile.println("Sun Mon Tue Wed Thu Fri Sat");
int numDays = getNumberofDays(month, year);
for(int day = 1; day <= numDays; day++){
int dayWeek = getDayofTheWeek(day, month, year);
for(int k = 0; k < dayWeek; k++)
outputFile.print(" ");
outputFile.printf("%3d ", day);
if(day % 7 == 0) {
outputFile.println("");
dayWeek = 0;
}
}
}
outputFile.close();
}
public static String getMonthName(int month){
String name;
switch(month){
case 1: name = "January";
break;
case 2: name = "February";
break;
case 3: name = "March";
break;
case 4: name = "April";
break;
case 5: name = "May";
break;
case 6: name = "June";
break;
case 7: name = "July";
break;
case 8: name = "August";
break;
case 9: name = "September";
break;
case 10: name = "October";
break;
case 11: name = "November";
break;
case 12: name = "December";
break;
default: name = "Unknown";
break;
}
return name;
}//method
public static int getNumberofDays(int month, int year){
int numDays;
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
numDays = isLeap(year)? 29:28;
break;
default:
numDays = 0;
break;
}
return numDays;
}//method
public static boolean isLeap(int year){
if(((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))
return true;
else
return false;
}
public static int getDayofTheWeek(int day, int month, int year){
int y = year - (14-month)/12;
int x = y+y/4 - y/100 + y/400;
int m = month + 12 * ((14-month)/12) -2;
int d = (day + x + (31*m)/12)%7;
return d;
}//method
}//class