In: Computer Science
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 type Day:
Thanks for the question, here is the class Day and DayTest. Have implemented both the classes in Java as the programming language was not explicitly mentioned.
The DayTest contains the test of various operations.
=========================================================================
public class Day {
private String
day;
// below are the only valid names for a day
private static final String
SHORT_NAMES[] = {"Sun",
"Mon", "Tue",
"Wed", "Thu",
"Fri", "Sat"};
public Day(String day) {
setDay(day);
}
// a.
private void setDay(String day)
{
boolean
validArgument = false;
for
(String name : SHORT_NAMES) {
if (day.equals(name)) {
this.day = day;
validArgument = true;
break;
}
}
// if the day name is not a valid name throw error
if
(!validArgument)
throw new
IllegalArgumentException("Invalid day name
entered");
}
// b.
public void printDay() {
System.out.println(day +
"day");
}
// c.
public String getDay() {
return
day;
}
// d. Return the next day.
public String nextDay() {
int
nextDay = 0;
for
(int i = 0; i <
SHORT_NAMES.length; i++) {
if
(SHORT_NAMES[i].equals(day))
{
nextDay = (i + 1) % 7;
break;
}
}
return
SHORT_NAMES[nextDay] +
"day";
}
// e.
public String previousDay()
{
int
previousDay = 0;
for
(int i = 0; i <
SHORT_NAMES.length; i++) {
if
(SHORT_NAMES[i].equals(day))
{
previousDay = i - 1 == -1 ? 6 : i - 1;
break;
}
}
return
SHORT_NAMES[previousDay] +
"day";
}
// f.
public String
dayAfterNDays(int n) {
int
index = 0;
for
(int i = 0; i <
SHORT_NAMES.length; i++) {
if
(SHORT_NAMES[i].equals(day))
{
index = i;
break;
}
}
int
indexOfNthDay = (index + n) % 7;
if
(indexOfNthDay < 0) indexOfNthDay = 7 + indexOfNthDay;
return
SHORT_NAMES[indexOfNthDay] +
"day";
}
}
=======================================================================
public class DayTest {
public static void
main(String[] args) {
Day today =
new Day("Mon");
System.out.print("Today is :
");today.printDay();
System.out.println("Next day: " +
today.nextDay());
System.out.println("Next day: " +
today.previousDay());
System.out.println("After 4 days :
" + today.dayAfterNDays(4));
System.out.println("After 13 days :
" + today.dayAfterNDays(13));
System.out.println("Previous -14 days :
" + today.dayAfterNDays(-14));
}
}
============================================================================
thanks a lot. Please do up vote please : )