The problem
Write a program that prompts the user to enter an integer for today’s day of the week (Sunday is 0, Monday is 1, . . ., and Saturday is 6). Also prompt the user to enter the number of days after today for a future day and display the future day of the week. Here is a sample run:
Enter today's day: 1
Enter the number of days elapsed since today: 3
Today is Monday and the future day is Thursday
Breaking it down
While you could consider only allowing a user to enter one through seven for the days of the week, the code below handles adding any number of days of the week. In java 8 adding days has been simplified by using DayOfWeek
enum that allows you to set the current day by calling DayOfWeek.of()
. Next by calling DayOfWeek.plus()
enables us to add any number of days.
public static void main(String[] strings) {
Scanner input = new Scanner(System.in);
System.out.print("Enter today's day: ");
int todayNumber = input.nextInt();
System.out.print("Enter the number of days elapsed since today: ");
int daysAfterNumber = input.nextInt();
input.close();
System.out.println("Today is " + DayOfWeek.of(todayNumber)
- " and the future day is "
- DayOfWeek.of(todayNumber).plus(daysAfterNumber));
}
Output
Enter today's day: 1
Enter the number of days elapsed since today: 2
Today is MONDAY and the future day is WEDNESDAY