Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads a string from the keyboard and tests whether it conta

ID: 3558073 • Letter: W

Question

Write a program that reads a string from the keyboard and tests whether it contains a valid date. Display the date and message that indicates whether it is valid. If it is not valid, also display a message explaining why it is not valid.

The input date will have the format mm/dd/yyyy. A valid month value mm must be from 1 to 12 (January is 1). the day value dd must be from 1 to a value that is appropriate for the given moth. September, April, June, and November each have 30 days. February has 28 days except for the leap years when it has 29. The remaining months all have 31 days each. A leap year is any year that is divisible by 4 but not divisible by 100 unless it is also divisible by 400.

Explanation / Answer

import java.text.SimpleDateFormat; import java.text.ParseException; public class DateTest { public boolean isValidDate(String inDate) { if (inDate == null) return false; //set the format to use as a constructor argument SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); if (inDate.trim().length() != dateFormat.toPattern().length()) return false; dateFormat.setLenient(false); try { //parse the inDate parameter dateFormat.parse(inDate.trim()); } catch (ParseException pe) { return false; } return true; } public static void main(String[] args) { DateTest test = new DateTest(); System.out.println(test.isValidDate("2004-02-29")); System.out.println(test.isValidDate("2005-02-29")); } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote