Write a Java program that prompts the user to input three positive integers: * t
ID: 3853469 • Letter: W
Question
Write a Java program that prompts the user to input three positive integers:
* the year, * the month, and * the calendar day
and prints the date in written long format, if the date is valid, or an error message, otherwise.
Note: You may explicitly assume that every date introduced is after Thursday, 14 September 1752, which corresponds to the adoption of the Gregorian calendar by Great Britain and its colonies.
Example: Suppose the user enter the year 2017, 7 as month, and 3 calenday day, then your program should output Monday, July 3rd, 2017. However, if the user introduces 2017, 2, and 29, for year, month, and calendar day respectively, your program should signal an error, since 2017 is not a leap year.
Explanation / Answer
import java.util.Scanner;
import java.util.Calendar;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int month;
int day;
int year;
boolean isTrue=true;
System.out.println("Enter your year:");
year = sc.nextInt();
System.out.println("Enter your month:");
month = sc.nextInt();
System.out.println("Enter your day:");
day = sc.nextInt();
if(month > 12){
isTrue = false ;
}else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
if (day <= 31){
isTrue = true;
}else{
isTrue = false;
}
}else if (month == 4 || month == 6 || month == 9 || month == 11){
if (day <= 30){
isTrue = true;
}else{
isTrue = false;
}
}else if (month == 2){// feb check
if (year % 4 == 0){
if (day <= 29){
isTrue = true;
}else{
isTrue = false;
}
}else if (year % 4 != 0){
if (day <= 28){
return;
}else{
isTrue = false;
}
}
}else{
isTrue = true;
}
String[] days =
{ "Thursday", "Friday", "Saturday", "Sunday","Monday", "Tuesday", "Wednesday"};
String[] monthNames={"Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"};
if (isTrue) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
int day_of_week = c.get(Calendar.DAY_OF_WEEK);
System.out.println(days[day_of_week-1]+", "+monthNames[month-1]+" "+day+", "+year );
}else {
System.out.println("False.");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.