Java Question
Q)There are 3 instance variables.
• month – an integer in the range 1-12.
• day - which stores an integer in the range 1-31
• year - any year between 2000 and 2025. Date provides the following functionality.
1. a zero-parameter constructor that stores the data representing Jan 1, 2000.
2. a parameterized constructor that accepts three parameters, one for each instance variable, and stores them if they are within acceptable ranges, or sets the date to Jan 1, 2000, if any value is out of range
3. a toString method that returns the date representation in the form yyyy-mm-day. For example, October 31, 2020, is represented as "2020-10-30"
4. • Add a boolean method comesBefore which accepts a Date as parameter and returns true if the date it is called on comes before the data that is sent as a parameter. For example, if date1 represents October 22, 2020, and date 2 represents October 30, 2020 then o data1.comesBefore(date2) return true o date2.comesBefore(date1) returns false o date1(comesBefore(date1) returns false
• Add a void (mutator) method nextDay that increments the day by 1. (For this problem we will assume that all months have 31 days.) For example, if the current date is February 31, 2020, then nextDay, will change the date to March 1, 2020. o if the current date is December 31, 2020, then nextDay, will change the date to January 1, 2021.
CODE IN JAVA:
public class Date {
int month ;
int day ;
int year ;
public Date() {
this.month = 1 ;
this.day = 1 ;
this.year = 2020 ;
}
public Date(int month, int day, int year) {
if(month >=1 && month
<= 12 && day >= 1 && day <= 31 &&
year >= 202 && year <= 2025) {
this.month =
month;
this.day =
day;
this.year =
year;
}
else {
this.month = 1
;
this.day = 1
;
this.year = 2020
;
}
}
public String toString() {
return this.year + "-" + this.month
+ "-" + this.day ;
}
public boolean comesBefore(Date d) {
if(this.year < d.year)
return true
;
if(this.year == d.year) {
if(this.month
< d.month)
return true;
if(this.month ==
d.month) {
if(this.day < d.day)
return true;
return false ;
}
return false
;
}
return false ;
}
public void nextDay() {
if(this.day != 31) {
this.day += 1
;
}
else {
this.day = 1
;
if(this.month !=
12)
this.month += 1 ;
else {
this.month = 1 ;
this.year += 1 ;
}
}
}
}
Get Answers For Free
Most questions answered within 1 hours.