JAVA: Design and implement the class Day that implements the day of the week in
ID: 3628042 • Letter: J
Question
JAVA: Design and implement the class Day that implements the day of the weekin 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
h) Write a program to test the class day - This program should ask the user to input a starting day and also enter a number of days into the future to be calculated.
Explanation / Answer
Day.java
public class Day {
private String[] days = {"SUN", "MON", "TUE", "WED" ,"THU" , "FRI", "SAT"};
private String day;
public Day() {
}
public void setDay(String day) {
this.day = day;
}
public String getDay() {
return this.day;
}
public void printDay(String day) {
System.out.println("The day is " + day);
}
public String nextDay() {
int i=0;
String nextDay = "";
for(String d: days) {
i++;
if(i==7)
i=0;
if(d.equalsIgnoreCase(day)) {
nextDay = days[i];
}
}
return nextDay;
}
public String previousDay() {
int i=-1;
String prevDay = "";
for(String d: days) {
i++;
if(d.equalsIgnoreCase(day)) {
if(i==0) {
i = 6;
prevDay = days[i]
}
else {
prevDay = days[i-1];
}
}
}
}
public String getDay(int value) {
int newIndex =0;
for(int i=0; i < days.length; i++) {
if(days[i].equals(day)) {
newIndex = i + value;
while(newIndex >= 7) {
newIndex %= 6;
}
}
}
return days[newIndex];
}
}
DayTest.java
class DayTest
{
public static void main(String[] args)
{
Day d = new Day();
d.setDay("WED");
d.printday(d.getDay());
d.printday(d.nextDay());
d.printday(d.previousDay());
d.printday(d.getDay(2));
d.printday(d.getDay(-2));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.