Design and implement the class Day that implements the day of the week in a prog
ID: 3641219 • 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 the day by adding certain days to the current day. For example, if the current day is Monday and we add 4 days, the day to be returned is Friday. Similarly, if today is Tuesday and we add 13 days, the day to be returned is Monday.
g. Add the appropriate constructors.
h. Write the definitions of the methods to implement the operations for the class Day as defined in a through g.
i. Write a program to test various operations on the class Day.
In java
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
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.