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

Write a class called DateConverter which has a static method that takes in a dat

ID: 3567064 • Letter: W

Question

Write a class called DateConverter which has a static method that takes in a date as a string (such as 01/21 or 1/21) and then returns a string with the date formatted with the alphanumeric month (such as January 21). This method throws two different exceptions DayException and MonthException, which you need to write yourself. The MonthException is thrown if the numeric month is not 1-12, and the DateException is thrown if the day is less than 0 or greater than the max possible day for that month. In other words:

Explanation / Answer

Here you go :)

//DateException Class

public class DayException extends DateException
{
   public DayException(String error)
   {
       super("Day Exception: "+error);
   }
}

//Month Exception class

public class MonthException extends DateException
{
   public MonthException(String error)
   {
       super("Month Exception: "+error);
   }
}

//DateException class (not needed but it is a good practise to keep all the exceptions under one super class)

public class DateException extends Exception
{
   public DateException(String error)
   {
       super(error);
   }
}

//DateConverter class

public class DateConverter {
   int[] days = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
   String[] names = { "January", "February", "March", "April", "May", "June",
           "July", "August", "September", "October", "December" };

   public String getInput(String in) throws DateException {
       String ret = "";
       String[] subs = in.split("/");
       int month = Integer.parseInt(subs[0]);
       int date = Integer.parseInt(subs[1]); // you can add try catch to
                                               // NumberFormatException

       if (month < 0 || month > 12) {
           throw new MonthException(
                   "Months must between 1 and 12 inclusively.");
       }
       if (date < 0 || date > days[month - 1]) {
           throw new DayException(
                   "This day is in the wrong range for the month provided.");
       }
       System.out.println("The date is " + names[month - 1] + " " + date);
       return ret;
   }

}

//Driver class

import java.util.Scanner;

public class DateConverterDriver {
   public static void main(String[] args) {
       DateConverter d = new DateConverter();
       Scanner keyboard = new Scanner(System.in);

       boolean quit = false;
       System.out.println("Welcome to the date converter!");
       while (quit == false) {
           System.out
                   .println("Enter a numeric date formatted as month/day or

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