Hello, currently I am having trouble performing this assignment which requires t
ID: 3815891 • Letter: H
Question
Hello, currently I am having trouble performing this assignment which requires that I use Switch statements and understand the use of object-oriented programming. I'm a beginner and I've never used switch statements before. I'd appreciate the help and thanks in advance.
Here are the directions:
"Your program should allow the user to input a date by prompting for the month, day and year in that order. The date is then checked for validity according to the rules of the Gregorian calendar. A message concerning the validity of the date is then printed. Each month has a valid range of days given by the rhyme – Thirty days hath September, April, June, and November. All the rest have 31, Except for February all alone, It has 28 each year, but 29 each leap year.
A leap year occurs when the year number is divisible by four, unless the year is divisible by 100 when the year is not a leap year. There is a further exception – if a year is divisible by 400 then it is a leap year."
Example Output:
Enter day: 29
Enter month: 2
Enter year: 2011
The date 2/29/2011 is not valid.
Alternatively,
Enter day: 30
Enter month: 10
Enter year: 2015
The date 10/30/2015 is valid.
Explanation / Answer
HI FRiend, You have not mentioned about any programming language.
Please try to mention all required details.
I have implemented in Simple Java using Switch.
Please let me know in case of any issue.
import java.util.Scanner;
public class ValidateDate {
public static boolean isLeapYear(int year) {
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter day: ");
int day = sc.nextInt();
System.out.print("Enter month:");
int month = sc.nextInt();
System.out.print("Enter year:");
int year = sc.nextInt();
int monthDayNumber;
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
monthDayNumber = 31;
break;
case 4:
case 6:
case 9:
case 11:
monthDayNumber = 30;
break;
case 2:
if(isLeapYear(year))
monthDayNumber = 29;
else
monthDayNumber = 28;
break;
default:
monthDayNumber = -1;
}
if(monthDayNumber == -1 || monthDayNumber < day || day < 1 || year < 1970){
System.out.println(month+"/"+day+"/"+year+" is not valid");
}else{
System.out.println(month+"/"+day+"/"+year+" is valid");
}
}
}
/*
Sample run:
Enter day: 29
Enter month:2
Enter year:2011
2/29/2011 is not valid
Enter day: 30
Enter month:10
Enter year:2015
10/30/2015 is valid
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.