首页 > 解决方案 > 如何使用此方法打印所有 12 个月的天数

问题描述

我有将用户输入作为年、月和日期的代码。我有三种方法,一种获取星期几,一种获取该月的天数,另一种计算该年是否为闰年。

当用户输入一年一个月和一个日期时,例如“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);
    }
}

标签: javamethodsint

解决方案


您走在正确的轨道上,但是您在循环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方法已经考虑了闰年,这应该足够了!


推荐阅读