198k views
0 votes
Write a program that prompts the user to enter the month and year and displays the number of days in the month. For example, if the user entered month 2 and year 2000, the program should display that February 2000 has 29 days. If the user entered month 3 and year 2005, the program should display that March 2005 has 31 days.Here is a sample run of this program:Enter a month in the year (e.g., 1 for Jan): 1Enter a year: 2009January 2009 has 31 daysExercise 3.11Liang, Y. Daniel. Introduction to Java Programming (8th Edition)

1 Answer

6 votes

Answer:

Following are the program in JAVA language

import java.util.Scanner; // import package

import java.util.Calendar; // import package

public class Main // class main

{

public static void main(String[] args) // main function

{

Scanner input = new Scanner(System.in); // for user input

Calendar calendar = Calendar.getInstance(); //get calendar instance for methods

int nYear , nMonth , date =1 , nDays;

String MonthOfName = "";

System.out.print(" Enter a month in the year :");

nMonth = input.nextInt(); //input Month

System.out.print("Enter a year :");

nYear = input.nextInt(); //Input Year

switch (nMonth) //Find month name via 1-12

{

case 1:

MonthOfName = "January";

nMonth = Calendar.JANUARY;

break;

case 2:

MonthOfName = "February";

nMonth = Calendar.FEBRUARY;

break;

case 3:

MonthOfName = "March";

nMonth = Calendar.MARCH;

break;

case 4:

MonthOfName = "April";

nMonth = Calendar.APRIL;

break;

case 5:

MonthOfName = "May";

nMonth = Calendar.MAY;

break;

case 6:

MonthOfName = "June";

nMonth = Calendar.JUNE;

break;

case 7:

MonthOfName = "July";

nMonth = Calendar.JULY;

break;

case 8:

MonthOfName = "August";

nMonth = Calendar.AUGUST;

break;

case 9:

MonthOfName = "September";

nMonth = Calendar.SEPTEMBER;

break;

case 10:

MonthOfName = "October";

nMonth = Calendar.OCTOBER;

break;

case 11:

MonthOfName = "November";

nMonth = Calendar.NOVEMBER;

break;

case 12:

MonthOfName = "December";

nMonth =Calendar. DECEMBER;

}

calendar.set(nYear, nMonth, date); // set date to calender to get days in month

nDays=calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // get no of days in month

System.out.println(MonthOfName + " " + nYear + " has " + nDays + " days."); //print output

}

}

Output:

Enter a month in the year : : 09

Enter a year : 2019

September 2019 has 30 days.

Step-by-step explanation:

In this program we have take two user input one for the month and other for the year Also take two variables which are used for storing the month name and no of days in a month. with the help of switch we match the cases and store the month value .After that set the date to calender with help of calendar.set(nYear, nMonth, date) method and To get the number of days from a month we use calendar.getActualMaximum(Calendar.DAY_OF_MONTH); method and finally print year and days.

User Raj Paliwal
by
5.4k points