Chris Redfieldea Chris Redfieldea - 24 days ago 7
Java Question

Write a program that prompts the user to enter a year and a month (first 3 letters, first letter uppercase) then displays the days of the month

Write a program that prompts the user to enter a year and the
first three letters of a month name (with the first letter in uppercase) and displays
the number of days in the month. Here is a sample run:

Enter a year: 2001

Enter a month: Jan

"Jan 2001 has 31 days"

Enter a year: 2016

Enter a month: Feb

"Jan 2016 has 29 days" (I do not understand this one specifically) My issue is with the Leap Year portion. I don't understand how to work it in with the rest of the program because the number of days are supposed to change. Nor do I understand why the month of "Feb" changed to "Jan" in the example. I need help reworking my program. All I can use is what is seen in the code below: """If statements and switch/case."""

import java.util.Scanner;

public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter a year: ");
int year = input.nextInt();
input.nextLine();

System.out.print("Enter a month: ");
String month = input.nextLine();
// Taken from the book per request of the instructor
boolean isLeapYear = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));

switch (month){
case "Jan":
case "Mar":
case "May":
case "July":
case "Aug":
case "Oct":
case "Dec":
System.out.println(month + " " + year + " has 31 days"); break;

case "Apr":
case "Jun":
case "Sep":
case "Nov":
System.out.println(month + " " + year + " has 30 days"); break;

case "Feb":
System.out.println(month + " " + year + " has 28 days");
}
}
}


I'd appreciate some help or any form of offering at this point. My instructor is away for the week which leaves me in complete darkness, without proper guidance.

Answer

I ran your program. I don't exactly know why you were getting that error about Feb 2016 resulting in Jan 2016 results. When I ran it, it ran exactly how it should. However, you did not return the correct amount of days in February when a leap year occurs. You wrote out the correct equation to determine a leap year, but you didn't use it.

    case "Sep":
    case "Nov":
        System.out.println(month + " " + year + " has 30 days"); break;

    case "Feb":
    if(isLeapYear)
    {
        System.out.println(month + " " + year + " has 29 days");
    }
        else
    {
            System.out.println(month + " " + year + " has 28 days");}
    }   
Comments