Question: Modify class Date of Fig. 8.7 to perform error checking on the initializer values for variables month, day and year (currently it validates only the
Modify class Date of Fig. 8.7 to perform error checking on the initializer values for variables month, day and year (currently it validates only the month and day). Provide a method nextDay to increment the day by one. Write a program that tests method nextDay in a loop that prints the date during each iteration to illustrate that the method works correctly. Test the following cases:
a) Incrementing into the next month and
b) Incrementing into the next year.
Fig. 8.7

I // Fig. 8.7: Date.java // Date class declaration. 2 3 4 5 6 7 8 9 10 II 12 13 14 15 16 17 18 19 20 21 22 23 24 25 N N N N N M M M M 26 27 28 29 30 31 32 33 34 35 36 37 38 public class Date { 39 40 41 42 43 44 45 } private int month; // 1-12 private int day; // 1-31 based on month private int year; // any year private static final int[] daysPerMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // constructor: confirm proper value for month and day given the year public Date(int month, int day, int year) { // check if month in range if (month 12) { throw new Illegal ArgumentException ( "month (" + month + ") must be 1-12"); } } // check if day in range for month if (day < 0 || (day> daysPerMonth [month] && ! (month == 2 && day throw new Illegal ArgumentException ("day (" + day + ") out-of-range for the specified month and year"); == == } // check for leap year if month is 2 and day is 29 if (month= 2 && day 29 && ! (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))) { throw new Illegal ArgumentException ("day (" + day + ") out-of-range for the specified month and year"); } // return a String of the form month/day/year public String toString() { return String.format("%d/%d/%d", month, day, year); 29))) { } this month = month; this.day = day; this.year = year; System.out.printf("Date object constructor for date %s %n", this);
Step by Step Solution
3.47 Rating (154 Votes )
There are 3 Steps involved in it
To update the Date class to perform error checking on the year as well as to provide a nextDay ... View full answer
Get step-by-step solutions from verified subject matter experts
