rahajengdwp

Untitled

Mar 6th, 2017
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. //8.7 Date.java
  2. //Date class declaration
  3.  
  4. public class Date
  5. {
  6. private int month; //1-12
  7. private int day; //1-31 based on month
  8. private int year; //any year
  9.  
  10. private static final int[] daysPerMonth = //days in each month
  11. {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  12.  
  13. // constructor: call checkMonth to confirm proper value for month;
  14. // call checkDay to confirm proper value for day
  15. public Date (int theMonth, int theDay, int theYear)
  16. {
  17. month = checkMonth( theMonth ); // validate month
  18. year = theYear; // could validate year
  19. day = checkDay( theDay ); // validate day
  20.  
  21. System.out.printf("Date object constructor for date %s\n", this );
  22. } //end Date constructor
  23.  
  24. //utility method to confirm poper 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
Advertisement
Add Comment
Please, Sign In to add comment