【发布时间】:2019-02-21 02:22:49
【问题描述】:
我的代码将用户输入作为年、月和日期。我有三种方法,一种获取星期几,一种获取该月的天数,另一种计算该年是否为闰年。
当用户输入年月和日期时,例如“2016 3 3”,我希望我的代码列出从 1 到 12 的月份,并在每个数字旁边列出该月的天数。我对所有三种方法的代码如下。
class Date {
int year, month, day;
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
/**
* This method returns the day of the week as an integer: 0 and 6: Sunday
* and Saturday 1 - 5: Weekdays
*/
public int getDayOfWeek() {
int y0 = year - (14 - month) / 12;
int x = y0 + y0 / 4 - y0 / 100 + y0 / 400;
int m0 = month + 12 * ((14 - month) / 12) - 2;
int d0 = (day + x + (31 * m0) / 12) % 7;
return d0;
}
/**
* This method returns the number of days in a given month an integer
*/
public int getDaysInMonth(int month) {
int daysInMonth = (int) (28 + (Math.floor(month / 8.0) + month) % 2 + 2 % month + 2 * Math.floor(1.0 / month));
if (month == 2 && isLeapYear()) {
daysInMonth += 1;
}
return daysInMonth;
}
public boolean isLeapYear() {
boolean isLeapYear = true;
if (year % 4 != 0) {
isLeapYear = false;
}
else {
if (year % 100 != 0) {
isLeapYear = true;
}
else if (year % 400 != 0) {
isLeapYear = false;
}
else {
isLeapYear = true;
}
}
return isLeapYear;
}
我在计算机科学专业的第一年,对此仍然很陌生,我一直盯着这段代码并在谷歌上搜索了一天的大部分时间,但似乎无法弄清楚任何事情,任何帮助将不胜感激。
我知道这是错误的,但这就是我目前所能想到的全部
public void printDaysInMonth() {
int m = getDaysInMonth(month);
System.out.println("Month " + " Days");
for (int i=0; i<12; i++) {
System.out.println(m);
}
}
【问题讨论】:
-
在
printDaysInMonth()的for循环中,考虑打印getDaysInMonth(i)。