Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. //Date class declaration
  2.  
  3. public class Date
  4. {
  5. private int month; // 1-12
  6. private int day; // 1-31 based on month
  7. private int year; // any year
  8.  
  9. private static final int[] daysPerMonth = // days in each month
  10. { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  11.  
  12. //constructor: call checkMonth to confirm proper value for month;
  13. //call checkDay to confirm proper value for day
  14. public Date( int theMonth, int theDay, int theYear )
  15. {
  16. month = checkMonth( theMonth ); // validate month
  17. year = theYear; // could validate year
  18. day = checkDay( theDay ); // validate day
  19.  
  20. System.out.printf(
  21. "Date object constructor for date %s\n", this);
  22. } // end Date constructor
  23.  
  24. //utility method to confirm proper month value
  25. private int checkMonth( int testMonth )
  26. {
  27. if( testMonth > 0 && testMonth <= 12 ) //validate month
  28. return testMonth;
  29. else // month is invalid
  30. throw new IllegalArgumentException( "month must be 1-12" );
  31. } // end method checkMonth
  32.  
  33. //utility method to confirm proper day value based on month and year
  34. private int checkDay( int testDay )
  35. {
  36. //check if day in range for month
  37. if( testDay > 0 && testDay <= daysPerMonth[ month ] )
  38. return testDay;
  39.  
  40. //check for leap year
  41. if( month == 2 && testDay == 29 && ( year % 400 == 0 ||
  42. ( year % 4 == 0 && year % 100 != 0 ) ) )
  43. return testDay;
  44.  
  45. throw new IllegalArgumentException(
  46. "day out-of-range for the specified month and year" );
  47. } // end method checkDay
  48.  
  49. //return a String of the form month/day/year
  50. public String toString()
  51. {
  52. return String.format( "%d/%d/%d", month, day, year );
  53. } //end method toString
  54. }//end class Date