【发布时间】:2017-10-02 07:53:05
【问题描述】:
首先抱歉我的英语不好。我已经制作了自己的日历程序。我刚收到1个问题。它不检查正确的闰年。
private final int[][] sizeOfMonth= {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
这是我的意见。
public int yearInput(String text){
String yearNumber = "";
boolean again = true;
while (again) {
System.out.print(text);
again = false;
try {
yearNumber = erfasseText();
int laenge = String.valueOf(yearNumber).length();
if (laenge != 4) {
again = true;
throw new Exception();
}
} catch (Exception e) {
this.output.yearWrongInput();
}
}
int converter = Integer.parseInt(jahresZahl);
return converter;
}
这是一个不同的类。
public int readYear() {
output.yearQuery();
int year = this.input.yearInput("Year: ");
return year;
}
闰年检查代码。
public int getSizeOfMonth(int year, int month) {
return this.sizeOfMonth[kalenderFunction.leapYear(year)][month];
}
我无法更改下面的代码,因为我的教授告诉过我。
boolean isLeapYear(int year) {
return ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)));
}
// 1 = true it is a leap year
// 2 = false it is not a leap year
int leapYear(int year) {
if (isLeapYear(year)) return 1;
else return 0;
}
最后一个是输出部分的缩短代码。
int monthSize= getSizeOfMonth(year, month);
for (int day= 1; day< monthSize; day++) {
System.out.print(getTwoLetters(day) + "\t");
if (weekdayInYear == 6) {
System.out.println();
// I know the weekdayInYear is not be initialized. thats just for next line.
}
}
我希望你能找到问题,因为对我来说,这段代码看起来很干净。而且我没有发现问题。
输出让我很困惑。如果我在输入中输入闰年,我会得到 2 月 28 天。 (必须是arraylist的1而不是0)
现在让我感到困惑如果我输入的不是闰年,我会得到 27 天。 (27 为什么) 数组中没有 27 的元素
*******************Febuary 2017*******************
Mo Tue We Thu Fr Sa Su
01 02 03 04 05
06 07 08 09 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27
我真的希望你能帮助我。我最后的希望。 最好的祝福, 面膜剂
【问题讨论】:
-
如果您将其简化为 minimal reproducible example,将会对我们有所帮助。
-
int day= 1; day< monthSize应该是<= monthSize。您正在停止迭代 1 以缩短。 -
throw-catch 不应该以这种方式使用...
-
旁注:您可能需要仔细重新阅读您的代码和 cmets。例如,您似乎有此评论
// 2 = false it is not a leap year和此实现int leapYear(int year) { if (isLeapYear(year)) return 1; else return 0; },正如您的评论所建议的那样,它返回 0 而不是 2。
标签: java arrays multidimensional-array io leap-year