NUMBER OF DAYS IN A MONTH
Write a method called isLeapYear with a parameter of type int named year.
The parameter needs to be greater than or equal to 1 and less than and equal to 9999. If the parameter is not in that range return false. Otherwise, if it is in the valid range, calculate if the year is a leap year and return true if it is, otherwise returns false.
[A year is a leap year if it is divisible by 4 not by 100, or it is divisible by 400]
Write another method getDaysInMonth with two parameters month and years. Both of type int
If parameter month is < 1 or > 12 return -1
If parameter year is < 1 or > 9999 return -1
This method needs to return the number of days in month. be careful about leap years (29 days in Feb)
[Use switch statements]
Soln package com.cnc;
public class Main {
public static void main(String[] args) {
System.out.println(isLeapYear(-2000));
System.out.println(getDaysInMonth(-2,2000));
}
public static boolean isLeapYear(int year){
if(year>=1 && year<=9999){
if(year%4==0 && !(year%100==0) || year%400==0)return true;
else return false;
}else return false;
}
public static int getDaysInMonth(int month,int year){
int days;
if((month<1 || month>12)||(year<1 || year>9999))return -1;
else
switch (month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days =(31);
break;
case 2:
if(year%4==0 && !(year%100==0) || year%400==0){
days=(29);
}else days=(28);
break;
case 4: case 6: case 9: case 11:
days=(30);
break;
default:
throw new IllegalStateException("Unexpected value: " + month);
}return days;
}
}