File name: dateexception.cpp Write a program that converts dates from numerical
ID: 3771567 • Letter: F
Question
File name: dateexception.cpp
Write a program that converts dates from numerical month/day format to alphabetic
month/day(for example1/31 or 01/31 corresponds to January 31). Throw a string
exception if the user enters anything other than a legal month number (integers
from 1 to 12. Similarly, throw a string exception if the user enters an invalid
day number(integers from 1 to either 29, 30, or 31, depending on the month). To
keep things simple, always allow 29 days for February.
Test your code by catching your exception
Explanation / Answer
import java.util.StringTokenizer;
import java.util.Scanner;
public class DateParser {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a date in the format MM/DD/YYYY:");
String input =sc.nextLine();
String month = "";
String day = "";
String year = "";
StringTokenizer tok = new StringTokenizer(input,"/");
int count =tok.countTokens();
if(count>0)
{
month=tok.nextTokens();
if(count>1)
{
day=tok.nextToken();
if(count>2)
{
year=tok.nextToken();
}
}
}
boolean done=false;
while(!done)
{
try{
String formatted = formatDate(month, day, year);
System.out.println("You entered: "+formatted);
done = true;
}
catch(MonthException me){
System.out.println("The month you entered(""+me.getMonth()+"") is not valid. Please re-enter the month [1-12]:");
month = sc.nextLine();
}
catch(DayException de) {
System.out.println("The day you entered (""+de.getDay()+"" is not valid. Please re-enter the day [1- " + de.getMaxDayForMonth()+"]:");
day = sc.nextLine();
}
catch(YearException ye){
System.out.print("The year you entered (""+ ye.getYear+"" is not valid. Please re-enter the year [1000-3000]:");
year = sc.nextLine();
}
}
}
public static String formatDate(String month, String day, String year)
throws MonthException, DayException, YearException {
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.