In: Computer Science
Use Java
(Find the number of days in a month)
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 2012, the program should
display that February 2012 has 29 days.
If the user entered month 3 and year 2015, the program should
display that March 2015 has 31 days.
Sample Run 1
Enter a month in the year (e.g., 1 for Jan): 2
Enter a year: 2012
February 2012 has 29 days
Sample Run 2
Enter a month in the year (e.g., 1 for Jan): 4
Enter a year: 2005
April 2005 has 30 days
Sample Run 3
Enter a month in the year (e.g., 1 for Jan): 2
Enter a year: 2006
February 2006 has 28 days
Sample Run 4
Enter a month in the year (e.g., 1 for Jan): 2
Enter a year: 2000
February 2000 has 29 days
Class Name: Exercise03_11
If you get a logical or runtime error, please refer
https://liveexample.pearsoncmg.com/faq.html.
import java.util.Scanner;
public class Pearson {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String arr[] = { " ", "January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" };
int days = 0;
System.out.print("Enter a month in the year: ");
int month = sc.nextInt();
System.out.println("Enter a year) ");
int year = sc.nextInt();
days = getDays(month, year);
System.out.println(arr[month] + " " + year + " has " + days + " days");
}
private static int getDays(int mm, int aYy) {
int res = -1;
if (mm == 1)
res = 31;
if (mm == 2)
if (isLeapYear(aYy))
res = 29;
else
res = 28;
if (mm == 3)
res = 31;
if (mm == 4)
res = 30;
if (mm == 5)
res = 31;
if (mm == 6)
res = 30;
if (mm == 7)
res = 31;
if (mm == 8)
res = 31;
if (mm == 9)
res = 30;
if (mm == 10)
res = 31;
if (mm == 11)
res = 30;
if (mm == 12)
res = 31;
return res;
}
private static boolean isLeapYear(int userYear) {
boolean leap = false;
// if any year is divisable by 4 than there are many chances for leap
// year except few
if (userYear % 4 == 0) {
// if it is divisable by 100 than it shoud also divisable by 400
// like 2000 etc
if (userYear % 100 == 0) {
// year is divisible by 400, so the year is a leap year
if (userYear % 400 == 0)
leap = true;
else
leap = false;
} else
leap = true;
} else
leap = false;
return leap;
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME