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.
This is an example run of the complete program:
CODE FOR MonthDays.java
Solution
import java.util.Scanner;
public class MonthDays
{
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);
}
}
private static int monthDays(int year, int month) {
// TODO Auto-generated method stub
if(month==2)
{
if(yearDays(year)==366)
{
return 29;
}
return 28;
}
if(month==1 || month==3 || month==5|| month==7|| month==8|| month==10|| month==12)
{
return 31;
}
return 30;
}
private static int yearDays(int year) {
// TODO Auto-generated method stub
if(year%400==0)
{
return 366;
}
else if(year%100==0)
{
return 365;
}
if(year%4==0)
{
return 366;
}
return 365;
}
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.format(\"%s is <= 0, try again.\ \ \", s);
continue;
}
return result;
}
}
}

