77.1k views
2 votes
Java:

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:
1. incrementing into the next month and
2. incrementing into the next year.

User Moltarze
by
8.0k points

1 Answer

3 votes

Answer:

Certainly! Here's an updated version of the Date class in Java, as per your requirements:

javaCopy code

public class Date { private int month; // 1-12 private int day; // 1-31 based on month private int year; // any year // constructor: confirm proper value for month and day given the year public Date(int month, int day, int year) { // validate month if (month < 1 || month > 12) { throw new IllegalArgumentException("Month must be between 1 and 12."); } // validate day int maxDay = getMaxDay(month, year); if (day < 1 || day > maxDay) { throw new IllegalArgumentException("Day must be between 1 and " + maxDay + " for the given month and year."); } this.month = month; this.day = day; this.year = year; } // helper method to determine the maximum day for a given month and year private int getMaxDay(int month, int year) { if (month == 2) { // February if (isLeapYear(year)) { return 29; } else { return 28; } } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else { return 31; } } // helper method to check if a year is a leap year private boolean isLeapYear(int year) (year % 4 == 0 && year % 100 != 0); // increment the day by one

User Spam
by
8.5k points

Related questions