user3602479
user3602479

Reputation: 3

Given a month and a year, return the number of days

The program is supposed to take a month and a year, and then return the number of days; however, it just asks for a couple more inputs and then gives output. I think the problem is with the Scanner instance, since I have tried with giving preset values, such as month = 2 and year = 2000, and it worked fine.

public static int getNumberofDays(int month, int year) {
    Scanner in = new Scanner(System.in);
    month = in.nextInt();
    year = in.nextInt();


    if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        checking which month is it
        if(month == 1 || month == 3 || month == 5 ||
                   month == 7 || month == 9 || month == 11)

        {
            return 31;
        } else if(month == 4 || month == 6 || month == 8 ||
                          month == 10 || month == 12) {
            return 30;
        } else {
            return 29;
        }
    } else {
        if(month == 1 || month == 3 || month == 5 || month == 7 ||
                   month == 9 || month == 11)

        {
            return 31;
        } else if(month == 4 || month == 6 || month == 8 ||
                          month == 10 || month == 12)

        {
            return 30;
        } else {
            return 28;
        }

    }
}

Upvotes: 0

Views: 115

Answers (1)

Makoto
Makoto

Reputation: 106508

This is weird:

Scanner in = new Scanner(System.in);
month = in.nextInt();
year = in.nextInt();

You're instantiating a new Scanner in your class and setting the parameters to the next integer value from it.

Why would you pass values in if that were the case?

Ditch the Scanner declaration inside of that method, so that what you pass in will actually be used, and advance the Scanner appropriately.

This is to say nothing of the logic errors you have - the days in each month is not correct. Case in point: November has 30 days, yet your program will return 31.

Here's a sample.

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Month?");
    int month = scan.nextInt();
    scan.nextLine();
    System.out.println("Year?");
    int year = scan.nextInt();
    scan.nextLine();
    System.out.println(getNumberOfDays(month, year));
}

Upvotes: 1

Related Questions