Monday, March 19, 2012

Lab 17: Exceptions

For this lab you will implement a Date class and a DateFormatException class. The Date class keeps the date in three private int member variables, called month, day, year. It has the following methods:
  • Date(int month, int day, int year): is the constructor
  • toString(): returns the date in a String of the form 2/2/2002
  • public static Date parseDate(String d) throws DateFormatException: tries to parse the string d into a viable date. If it succeeds then it creates a new date and returns it. If it fails then it throws the DateFormatException. d is a viable date if it is in the form "m/d/y" where m is an integer between 1 and 12, d is an integer between 1 and 31, and y is an integer.

For example, if you were to run this main:
public static void main(String[] args){
  Date d = null;
  Scanner keyboard = new Scanner(System.in);
  boolean goodDate = false;
  do {
   System.out.print("Enter a date:");
   String w = keyboard.next();
   try{
    d = Date.parseDate(w);
    goodDate = true;
   } catch (DateFormatException e){
    System.out.println("Bad user! " + w + " is not a date I understand.");
   }
  } while (! goodDate);
  System.out.println("Finally! You entered a well-formatted date: " + d);
 }

it could result in the following interaction:
Enter a date:chanchan
Bad user! chanchan is not a date I understand.
Enter a date:44/44/44
Bad user! 44/44/44 is not a date I understand.
Enter a date:1/44/2012
Bad user! 1/44/2012 is not a date I understand.
Enter a date:44/24/2012
Bad user! 44/24/2012 is not a date I understand.
Enter a date:3-3-2012
Bad user! 3-3-2012 is not a date I understand.
Enter a date:3/19/2012
Finally! You entered a well-formatted date: 3/19/2012

TIP: Checkout Integer.parseInt() and String.split(), they are your secret weapon.

HACKER FYI: parseDate is a static method that creates new instances of the class. We call methods like this factories.

No comments: