Design and implement the class Day that implements the day of the week in a prog
ID: 3624556 • Letter: D
Question
Design and implement the class Day that implements the day of the week
in a program. The class Day should store the day, such as Sun for
Sunday. The program should be able to perform the following operations
on an object of the type Day:
a) Set the day
b) Print the day
c) Return the day
d) Return the next day
e) Return the previous day
f) Calculate and return a day by adding # of days to current day.
(ie. if current day is Monday and we add 3 days then new day
is Thursday)
g) Add the appropiate constructors // default & set constructors
Explanation / Answer
import java.util.*;
public class Day {
private final List<String> DAYS = Arrays.asList(new String[] {"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"});
String dayString;
int dayInt;
public Day(String day) {
dayString = day;
dayInt = dayToInt(day);
}
public Day(int day) {
dayInt = day;
dayString = DAYS.get(day);
}
public String toString() {
return dayString;
}
public void setDay(String day) {
dayString = day;
dayInt = dayToInt(day);
}
public void setDay(int day) {
dayInt = day;
dayString = DAYS.get(day);
}
public String getDay() {
return dayString;
}
public Day getNextDay() {
return new Day((dayInt+1) % 7);
}
public Day getPreviousDay() {
int prevDay = (dayInt - 1) % 7;
if (prevDay < 0) prevDay += 7;
return new Day(prevDay);
}
public Day addDays(int daysToAdd) {
return new Day((dayInt+daysToAdd) % 7);
}
private int dayToInt(String day) {
return DAYS.indexOf(day.toUpperCase());
}
public static void main(String[] args) {
Day sunday = new Day("Sunday");
System.out.println("Today is "+sunday);
System.out.println("Yesterday was "+sunday.getPreviousDay());
System.out.println("Tomorrow will be "+sunday.getNextDay());
System.out.println("Nine days from now will be "+sunday.addDays(9));
Day tuesday = new Day(2);
System.out.println("Now the day is "+tuesday);
}
}
pls rate thanks
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.