Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a program that uses a switch statement and case statements to calculate t

ID: 3676059 • Letter: C

Question

Create a program that uses a switch statement and case statements to calculate the number of days in any given month based upon a users input. | February is a unique month. So the case for February will need a_ If... else to capture the two possible options for the number of days in February based upon leap year. Use the new Scanner (System.in); method for input. Make sure the program can deal with any integer input. If a number entered does not correspond to a month of the year print "Invalid Month."

Explanation / Answer


import java.util.Scanner;

public class PrintCalendar {

/** Main method */

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter full year (e.g., 1999): ");

    int year = scanner.nextInt();

    System.out.print("Enter month in number between 1 and 12: ");

    int month = scanner.nextInt();
    if ( month > 12 || month == 0 ) {
    System.out.println( "Invalid Month "); }
    else System.out.println(year + " " + (getMonthName(month) + " " + "has " + getNumberOfDaysInMonth(year,month) + " " + "days"));
   
     }

static String getMonthName(int month)
{

    String monthName = null;

    switch (month)
   {

      case 1: monthName = "January"; break;

      case 2: monthName = "February"; break;

      case 3: monthName = "March"; break;

      case 4: monthName = "April"; break;

      case 5: monthName = "May"; break;

      case 6: monthName = "June"; break;

      case 7: monthName = "July"; break;

      case 8: monthName = "August"; break;

      case 9: monthName = "September"; break;

      case 10: monthName = "October"; break;

      case 11: monthName = "November"; break;

      case 12: monthName = "December";

    }


    return monthName;

}

/** Get the number of days in a month */

static int getNumberOfDaysInMonth(int year, int month)
{

    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)

      return 31;

    if (month == 4 || month == 6 || month == 9 || month == 11)

      return 30;

    if (month == 2) {
    if(isLeapYear(year))
                {
                return 29;
            }
            else
            {
                    return 28;
            }
      }

  
    return 0; // If month is incorrect
       
}

/** Check for leap year */

static boolean isLeapYear(int year) {

    return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote