Mmrug Mmrug - 17 days ago 11
Java Question

Days of the week

I am trying to make a program that gets the day from the user input and then tells them the day before and the day after.The user should also be able to input how many days to add and the program should output that day.

example user enters 1 = Monday, tomorrow is = 2 Tuesday yesterday was = 3 Sunday

if user says its Monday(1) and adds 12 days the output should be Saturday(6)

The problem is whenever "theWeekDay" is greater than 7 it outputs nothing because TheDay(); doesn't have a condition for something greater than 7. Please help me!

Thanks you so much!

import java.util.Scanner;
import java.util.Scanner;

public class Problem_3 {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int theWeekDay;
System.out.println("What Day Is It?");
theWeekDay = input.nextInt();
Days one = new Days(theWeekDay);
System.out.println("Today It Is: ");
one.TheDay(theWeekDay);
System.out.println("Yesterday It Was: ");
one.PreviousDay(theWeekDay);
System.out.println("Tomorrow It Is: ");
one.NextDay(theWeekDay);
System.out.println("How Many Days To Add?");
int x = input.nextInt();
System.out.println("Now It Is: ");
one.AddedDays(x);
}
}

class Days {
private int theWeekDay;

public Days(int theWeekDay) {
this.theWeekDay = theWeekDay;
}

public int getTheWeekDay() {
return theWeekDay;
}

public void setTheWeekDay(int theWeekDay) {
this.theWeekDay = theWeekDay;
}

public int TheDay(int theWeekDay) {
// an arra days of week + then add days in it
if (theWeekDay == 0) {
theWeekDay = theWeekDay + 7;
}

if (theWeekDay == 1) {
System.out.println("Monday");
} else if (theWeekDay == 2) {
System.out.println("Tuesday");
} else if (theWeekDay == 3) {
System.out.println("Wednsday");
} else if (theWeekDay == 4) {
System.out.println("Thursday");
} else if (theWeekDay == 5) {
System.out.println("Friday");
} else if (theWeekDay == 6) {
System.out.println("Saturday");
} else if (theWeekDay == 7) {
System.out.println("Sunday");
}
return theWeekDay;
}

public int PreviousDay(int theWeekDay) {
theWeekDay = theWeekDay - 1;
return TheDay(theWeekDay);
}

public int NextDay(int theWeekDay) {
theWeekDay = theWeekDay + 1;
if (theWeekDay > 7) {
theWeekDay = 1;
}
return TheDay(theWeekDay);
}

public int AddedDays(int AddedDays) {
getTheWeekDay();
theWeekDay = theWeekDay + AddedDays;
return TheDay(theWeekDay);
}
}

Answer

If you want to assume value greater that 7 as valid, you should definitely use modulo operation. Something like this:

if(theWeekDay > 7) {
    theWeekDay = theWeekDay % 7;
}

Otherwise you should throw and exception.

Comments