javamethodsint

How do I print the number of days of all 12 months using this method


I have code that takes user input as the year, the month and then the date. I have three methods, one gets the day of the week, one gets the amount of days in that month, and the other calculates whether or not that year is a leap year.

When a user enters a year a month and a date, for example "2016 3 3" I want my code to then list the months from 1-12 and next to each number the amount of days in that month. The code I have for all three methods is as follows.

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;
} 

I'm in my first year of computer science and am still very fresh to this, i've been staring at this code and googling for the better part of a day and can't seem to figure anything out, any help would be appreciated.

I know this is wrong but this is all I've been able to come up with so far

public void printDaysInMonth() {
    int m = getDaysInMonth(month);
    System.out.println("Month  " + "  Days");
    for (int i=0; i<12; i++) {
        System.out.println(m);
    }
}

Solution

  • You're on the right track, but you're assigning your m variable outside of the for loop, and thus printing the same month every time. Instead, try assigning it and printing it inside the loop you already have:

    public void printDaysInMonth() {
        for (int i = 1; i <= 12; i++) {
            int m = getDaysInMonth(i);
            System.out.println("Month " + i + " has " + m  + "days.");
        }
    }
    

    Since your getDaysInMonth method already accounts for leap years, this should be enough!