0

I am trying to solve this problem, in which you enter a number 1-7 which corresponds to the days of the week, (Monday-Sunday) then you add a number between (0-20) and the program returns the day of the week. My current solution works except for 'Sunday'.

public static void main(String[] args) {
    int day;
    int num;
    int newDay;
    String [] days = new String[] {"Monday", "Tuesday", "Wednesday", "Thursday",
                                    "Friday", "Saturday", "Sunday"};
    System.out.println("Enter the day and the number to add");
    Scanner scnr = new Scanner(System.in);
    day = scnr.nextInt();
    num = scnr.nextInt();
    newDay = (num + day) % 7;
    System.out.println(newDay);
    System.out.println("The new day is " + days[newDay - 1] );
}

As you can see, if the program were to hit "Sunday," the array would go out of bounds. I could easily just say "if newDay = 0, set newDay = 7" but I want to see if there's a different solution.

Thanks for the help!

  • Think about what will happen if "newDay" equals 0, then you can realize where the problem is. – LHCHIN Oct 11 '17 at 03:08

1 Answers1

2

I don't fully understand the math/logic behind what you are doing, but I think I can explain (and correct) the error. In the following line of code:

newDay = (num + day) % 7;

The values which newDay can take on must be between 0 and 6 inclusive. So it seems to me that you would want to access your array of days as follows:

System.out.println("The new day is " + days[newDay]);

This makes sense because days has seven elements, addressable by indices from 0 to 6 inclusive.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360