Modify the Date class in Fig. 8.7 by adding a new method called nextDay() that increments the Date by 1 when called and returns a new Date object. This method should properly increment the Date across Month boundary (i.e from the last day of the month to the first day of the next month).
Write a program called DateTest that asks the user to enter 3 numbers (one at a time) corresponding to Month, Day and Year. The first two will be 2 digits(Month and Day) and 3rd will be 4 digits(Year). Read the numbers and create a corresponding Date object. Write a loop that increments this Date 3 times by calling nextDay()and displays each Date in the format mm/dd/yyyy on the console. You MUST use nextDay() to generate the dates. You CANNOT HARD CODE the output.
Your program should work for any valid data that user
enters. (Assume that the user will enter VALID month,day and year
numbers).
You can assume that all dates will be in the same year
2020.
Example:
If user enters 07 30 and 2020. The following should be
displayed:
07/30/2020
07/31/2020
08/01/2020
Upload 2 Java files to Canvas: Date.java and DateTest.java.
Program Code Screenshot :
Sample Output :
Program Code to Copy
import java.util.Scanner; class Date{ int month,day,year; //Argumented constructor public Date(int month, int day, int year) { this.month = month; this.day = day; this.year = year; } @Override public String toString(){ return month/10+""+month%10+"/"+day/10+""+day%10+"/"+year; } public void nextDay(){ //Days in the month int days[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; //If year is leap, increase number of days in february if(year%400==0 || (year%4==0 && year%100!=0)){ days[2]++; } //Increment the day this.day++; //Move to next month if(day>days[month]){ day = 1; month++; } //Move to next year if(month>12){ month = 1; year++; } } } class DateTest{ public static void main(String[] args) { //Scanner to read the data Scanner obj = new Scanner(System.in); //Read month, day and year System.out.print("Enter Month, Day and year "); int month = obj.nextInt(); int day = obj.nextInt(); int year = obj.nextInt(); //Create date Date date = new Date(month,day,year); System.out.println(date); //Move to next days date.nextDay(); date.nextDay(); System.out.println(date); } }
Get Answers For Free
Most questions answered within 1 hours.