In: Computer Science
As you know, the number of days in each month of our calendar
varies: • February has 29 days in a leap year, or 28 days
otherwise. • April, June, September, and November have 30 days. •
All other months have 31 days. Usually, years that are divisible by
4 (e.g., 2008, 2012, 2016) are leap years. However, there’s an
exception: years that are divisible by 100 (e.g., 2100, 2200) are
not leap years. But there’s also an exception to that exception:
years that are divisible by 400 (e.g., 1600, 2000) are leap
years.
Within your Lab3HW folder, write a program named DaysInMonth.java
that asks the user to enter a month (1-12) and year (1000-3000).
Your program should then show the number of days in that month. If
the user enters a month or year beyond the specified ranges, show an
appropriate error message.
Here are some examples of what your completed program might look
like when you run it. Underlined parts indicate what you type in as
the program is running.
Example 1
Enter month (1-12): 0 Enter year (1000-3000): 2001 Error - month
and/or year out of bounds.
1
Example 2
Enter month (1-12): 2 Enter year (1000-3000): 2016 2/2016 contains
29 days.
Example 3
Enter month (1-12): 2 Enter year (1000-3000): 2900 2/2900 contains
28 days.
import java.util.Scanner;
public class DaysInMonth {
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
System.out.println("Enter
month(1-12): ");
int month= sc.nextInt();
System.out.println("Enter
year(1000-3000)");
int year = sc.nextInt();
int days = getDays(month,
year);
if(month<1 || month>12 ||
year<1000 || month>3000){
System.out.println("month and/or year out of bounds.");
}
System.out.println(month + "/" +
year + " has " + days + " days");
}
//using switch case it checks the days for given month
private static int getDays(int mm, int aYy) {
int res = -1;
switch (mm) {
case 1:
res = 31;
break;
case 2:
if
(isLeap(aYy))
res = 29;
else
res = 28;
break;
case 3:
res = 31;
break;
case 4:
res = 30;
break;
case 5:
res = 31;
break;
case 6:
res = 30;
break;
case 7:
res = 31;
break;
case 8:
res = 31;
break;
case 9:
res = 30;
break;
case 10:
res = 31;
break;
case 11:
res = 30;
break;
case 12:
res = 31;
break;
}
return res;
}
private static boolean isLeap(int year) {
boolean leap = false;
// if any year is divisable by 4
than there are many chances for leap
if (year % 4 == 0) {
// if it is
divisable by 100 than it shoud also divisable by 400
if (year % 100
== 0) {
// year is divisible by 400, so the year is a
leap year
if (year % 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 you
If you like my answer please rate and help me it is very Imp for me