java问题与循环转发
所以我的循环有一个问题,我的目的是在进入下一行之前填满整个月,就像这样
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();
}
# 1 楼答案
正如Perdi Estaquel所说,你又错过了一个循环
每月只启用一次天输出,您需要这样做
# 2 楼答案
您缺少一个循环
外部循环从最左边的月份到最右边的月份(总共3个)。但这只会给你一句话
你必须用另一个能穿过所有线的环来包裹它
# 3 楼答案
你的方法有点令人头痛。我并不是说它不起作用,但这样的嵌套循环太复杂了
您可以定义一个Month类,该类将有
header()
和getLine(int lineNumber)
方法您还可以有一个
Quarter
类,该类将有header()
和getLine(int lineNumber)
方法。它将包含三个月的对象然后,您可以在
Quarter
对象中循环(一年4个)并打印标题,后跟6行