所以我的循环出现了问题,其目的是在进入下一行之前先完成整个月,就像这样
January 2000 February 2000 March 2000
|S M Tu W Th F S| |S M Tu W Th F S| |S M Tu W Th F S|
1 1 2 3 4 5 1 2 3 4
2 3 4 5 6 7 8 6 7 8 9 10 11 12 5 6 7 8 9 10 11
9 10 11 12 13 14 15 13 14 15 16 17 18 19 12 13 14 15 16 17 18
16 17 18 19 20 21 22 20 21 22 23 24 25 26 19 20 21 22 23 24 25
23 24 25 26 27 28 29 27 26 27 28 29 30 31
但是我的结果看起来像这样-
January 2000 February 2000 March 2000
|S M Tu W Th F S||S M Tu W Th F S||S M Tu W Th F S|
1 1 2 3 4 5 1 2 3 4
April 2000 May 2000 June 2000
|S M Tu W Th F S||S M Tu W Th F S||S M Tu W Th F S|
1 1 2 3 4 5 6 1 2 3
July 2000 August 2000 September 2000
|S M Tu W Th F S||S M Tu W Th F S||S M Tu W Th F S|
1 1 2 3 4 5 1 2
October 2000 November 2000 December 2000
|S M Tu W Th F S||S M Tu W Th F S||S M Tu W Th F S|
1 2 3 4 5 6 7 1 2 3 4 1 2
可以做些什么或添加些什么才能使其完全正常运行并通过?我觉得我有一个循环问题,但我确实无法查明问题
public static int day(int month, int day, 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;
}
public static boolean isLeapYear(int year) {
if ((year % 4 == 0) && (year % 100 != 0))
return true;
if (year % 400 == 0)
return true;
return false;
}
public static void main(String[] args) {
// take in command line argument to determine the month and year
int month = 0;
int year = 2000;
String[] months = { "", // left empty so that months[1] = "January"
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
"November", "December" };
// days[i] = number of days in month i
int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for (month = 1; month < 12;) {
// check for leap year
if (month == 2 && isLeapYear(year))
days[month] = 29;
// print calendar header
for (int f = 0; f < 3; f++) {
System.out.print(" " + months[month] + " " + year + " ");
month++;
}
System.out.println();
for (int f = 0; f < 3; f++) {
System.out.print("|S M Tu W Th F S|");
}
System.out.println();
// print the calendar
month -= 3;
for (int f = 0; f < 3; f++) {
int d = day(month, 1, year);
for (int i = 0; i < d; i++)
System.out.print(" ");
for (int i = 1; i <= days[month]; i++) {
System.out.printf("%2d ", i);
if (((i + d) % 7 == 0) || (i == days[month])) {
if(month<12)
month++;
break;
}
}
}
System.out.println();
}
答案 0 :(得分:1)
您缺少一个循环。
外循环从最左边的月份到最严重的月份(总共3个)。但这只会给你一行。
您必须用另一个循环包装它,该循环将遍历所有行。
答案 1 :(得分:0)
正如Perdi Estaquel所说,您还错过了一个循环。
for (month = 1; month < 12;) {
}
仅启用每月一次的天数输出,您需要这样做。
for (month = 1; month < 12;) {
// month and header output stay unchanged
for (int calendarLine = 1; calenderLine <= 5; calenderLine++) {
// your calender output here
}
}
答案 2 :(得分:-1)
您的方法有点令人头疼。我并不是说这行不通,但是这样的嵌套循环太复杂了。
您可以定义一个具有header()
和getLine(int lineNumber)
方法的Month类。
您还可以拥有一个Quarter
类,该类将具有header()
和getLine(int lineNumber)
方法。它包含三个Month对象。
然后您可以遍历Quarter
对象(一年4个)并打印标题,后跟6行。