Cycling through days of the week

Hi.
I’m trying to write a code that cycles through the days of the week. Specifically, if today is Saturday, my code has to print

today is Saturday
tomorrow is Sunday
the day after tomorrow is Monday

and this has to work for every day of the week as detected by the computer’s clock (e.g. if Friday is detected, the code should print … is Friday, …is Saturday and …is Sunday). Here’s my solution:

import java.text.SimpleDateFormat;
import java.util.*;

int day = int(new SimpleDateFormat("u").format(new Date()));

String today = "";
String tomorrow = "";
String dayAfterTomorrow = "";

int week[] = {1, 2, 3, 4, 5, 6, 7};
String daysOfWeek[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

for (int i = 0; i < week.length; i++) {
  if ((day == week[i]) && (i < 5)) {
    today = "today is " + daysOfWeek[i];
    tomorrow = "tomorrow is " + daysOfWeek[i+1];
    dayAfterTomorrow = "the day after tomorrow is " + daysOfWeek[i+2];
  } else if ((giorno == settimana[i]) && (i == 5)) {
    tomorrow = "today is " + daysOfWeek[i];
    domani = "tomorrow is " + daysOfWeek[i+1];
    dayAfterTomorrow = "the day after tomorrow is " + daysOfWeek[0];
  } else if ((giorno == settimana[i]) && (i == 6)) {
    today= "today is " + daysOfWeek[i];
    tomorrow = "tomorrow is " + daysOfWeek[0];
    dayAfterTomorrow = "the day after tomorrow is " + daysOfWeek[1];
  }
}

println(today);
println(tomorrow);
println(dayAfterTomorrow);

I’m pretty sure that there are too many lines of code and a more elegant solution could be found. In particularly I remember of having seen a solution to cycle through the array using modulo… but I’m not able to figure out how it should work.
Can you please help me?

you need modulus :slight_smile:

import java.text.SimpleDateFormat;
import java.util.*;

int day = int(new SimpleDateFormat("u").format(new Date()));

day -= 1;

String today = "";
String tomorrow = "";
String dayAfterTomorrow = "";

String daysOfWeek[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

today = "today is " + daysOfWeek[day];
tomorrow = "tomorrow is " + daysOfWeek[(day+1)%7];
dayAfterTomorrow = "the day after tomorrow is " + daysOfWeek[(day+2)%7];

println(today);
println(tomorrow);
println(dayAfterTomorrow);
2 Likes

I will definitely! :rofl: