BenitoDannes

Untitled

Mar 6th, 2017
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.03 KB | None | 0 0
  1. /**
  2.  * Fig. 8.7: Date.java
  3.  *
  4.  * Benito Dannes
  5.  * 5 March 2017
  6.  */
  7.  
  8. // Date class declaration
  9. public class Date
  10. {
  11.     private int month; // 1 - 12
  12.     private int day; // 1 - 31 based on month
  13.     private int year; // any year
  14.    
  15.     private static final int[] daysPerMonth = // days in each month
  16.         {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  17.        
  18.     // Constructor: call checkMonth to confirm proper value for month;
  19.     // call checkDay to confirm proper value for day
  20.     public Date (int theMonth, int theDay, int theYear)
  21.     {
  22.         month = checkMonth (theMonth); // validate month
  23.         year = theYear; // could validate year
  24.         day = checkDay (theDay); // validate day
  25.        
  26.         System.out.printf("Date object constructor for data %s\n", this);
  27.     } // end Date constructor
  28.    
  29.     // utility method to confirm proper month value
  30.     private int checkMonth (int testMonth)
  31.     {
  32.         if (testMonth > 0 && testMonth <= 12) // validate month
  33.         {
  34.             return testMonth;
  35.         }
  36.         else // month is invalid
  37.         {
  38.             throw new IllegalArgumentException ("month must be 1-12");
  39.         }
  40.     } // end method checkMonth
  41.    
  42.     // utility method to confirm proper day value based on month and year
  43.     private int checkDay (int testDay)
  44.     {
  45.         // check if day in range for month
  46.         if (testDay > 0 && testDay <= daysPerMonth[month])
  47.         {
  48.             return testDay;
  49.         }
  50.        
  51.         // check for leap year
  52.         if (month == 2 && testDay == 29 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)))
  53.         {
  54.             return testDay;
  55.         }
  56.        
  57.         throw new IllegalArgumentException ("day-out-of-range for the specified month and year");
  58.     } // end method checkDay
  59.    
  60.     // return a String of the form month/day/year
  61.     public String toString()
  62.     {
  63.         return String.format ("%d/%d/%d", month, day, year);
  64.     } // end method toString
  65. } // end class Date
Advertisement
Add Comment
Please, Sign In to add comment