ilminottaken

Untitled

Oct 5th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Fig. 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(
  22.             "Date object constructor for date %s\n", this );
  23.         } // end Date constructor
  24.  
  25.         // utility method to confirm proper month value
  26.         private int checkMonth( int testMonth )
  27.         {
  28.        
  29.             if ( testMonth > 0 && testMonth <= 12 ) // validate month
  30.                 return testMonth;
  31.    
  32.             else // month is invalid
  33.                 throw new IllegalArgumentException( "month must be 1-12" );
  34.                 // end method checkMonth
  35.         }
  36.  
  37.         // utility method to confirm proper day value based on month and year
  38.         private int checkDay( int testDay )
  39.         {
  40.             // check if day in range for month
  41.             if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
  42.                 return testDay;
  43.  
  44.             // check for leap year
  45.             if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
  46.                 ( year % 4 == 0 && year % 100 != 0 ) ) )
  47.                 return testDay;
  48.  
  49.             throw new IllegalArgumentException(
  50.                 "day out-of-range for the specified month and year" );
  51.         } // end method checkDay
  52.  
  53.         // return a String of the form month/day/year
  54.         public String toString()
  55.         {
  56.             return String.format( "%d/%d/%d", month, day, year );
  57.         } // end method toString
  58.     } // end class Date
Add Comment
Please, Sign In to add comment