我有代码将用户输入作为年份,月份和日期。我有三种方法,一种获取一周中的一天,一种获取该月的天数,另一种计算该年是否为闰年。
当用户输入一年中的一年和一个日期时,例如“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;
}
我正处于计算机科学的第一年,对此仍然非常新鲜,我一直盯着这段代码,并且在一天中的大部分时间里用Google搜索,似乎无法解决任何问题,任何帮助都将受到赞赏。
我知道这是错的,但到目前为止,我已经能够提出这一切
public void printDaysInMonth() {
int m = getDaysInMonth(month);
System.out.println("Month " + " Days");
for (int i=0; i<12; i++) {
System.out.println(m);
}
}
你是在正确的轨道上,但是你在m
循环之外分配你的for
变量,因此每次打印相同的月份。相反,尝试分配它并将其打印在您已有的循环中:
public void printDaysInMonth() {
for (int i = 1; i <= 12; i++) {
int m = getDaysInMonth(i);
System.out.println("Month " + i + " has " + m + "days.");
}
}
由于你的getDaysInMonth
方法已经占了闰年,这应该足够了!