File MonthDaysjava contains an incomplete program that takes
File MonthDays.java contains an incomplete program, that takes as input from the user a year and a month, and prints: the number of days in that year, and the number of days in that specific month of the year. Complete that program, by defining two functions.
The first function is called yearDays, and should satisfy the following specs:
yearDays takes one argument, called year, which is an integer greater than 0 (we will only test your code with such values).
If year is a leap year, then yearDays(year) returns 366.
Otherwise, yearDays(year) returns 365.
The second function is called monthDays, and should satisfy the following specs:
monthDays takes two arguments, called year, month. Argument year is an integer greater than 0 (we will only test your code with such values). The month argument is an integer between 1 and 12 (we will only test your code with such values).
The function returns the number of days in that month. Unless the month is 2 (for February), the result does not depend on the year. If the month is 2, then obviously the result should be 28 or 29, depending on whether the year is a leap year.
IMPORTANT: you are NOT allowed to modify in any way the main function.
Note that, as that program indicates, the rules for leap years are a bit more complicated than simply checking if a year is a multiple of four. More specifically, a year is a leap year if AT LEAST ONE of the following two conditions holds:
The year is a multiple of 4 and the year is NOT a multiple of 100.
The year is a multiple of 400.
This is an example run of the complete program:
Solution
import java.util.Scanner;
public class MonthDays
{
public static int userInteger(String message)
{
Scanner in = new Scanner(System.in);
int result;
while (true)
{
System.out.printf(message);
String s = in.next();
if (s.equals(\"q\"))
{
System.out.printf(\"Exiting...\ \");
System.exit(0);
}
try
{
result = Integer.parseInt(s);
}
catch (Exception e)
{
System.out.printf(\"%s is not a valid number, try again.\ \ \", s);
continue;
}
if (result <= 0)
{
System.out.printf(\"%s is <= 0, try again.\ \ \", s);
continue;
}
return result;
}
}
public static int yearDays(int y)
{
if(y%4 == 0) return 366;
else return 365;
}
public static int monthDays(int y,int m)
{
boolean l=false;
if(yearDays(y)==366) l=true;
if(m==4 || m== 6 || m==9 || m==11)
return 30;
else if(m==2)
{
if(l)
return 29;
else return 28;
}
else return 31;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
while (true)
{
int year = userInteger(\"Enter a year (must be > 0): \");
int month = userInteger(\"Enter a month (must be between 1 and 12): \");
if (month > 12)
{
System.out.printf(\"Invalid month.\ \ \");
continue;
}
int result = yearDays(year);
int result2 = monthDays(year, month);
System.out.printf(\"Year %d has %d days.\ \", year, result);
System.out.printf(\"Month %d, %d has %d days.\ \ \", month, year, result2);
}
}
}

