user3390848 user3390848 - 1 month ago 18
Java Question

Cycle through an array

lets say you have an array that has the days of the week in it:

String days[]={"monday","tuesday","wednesday","thursday",
"friday","saturday","sunday"};


Now lets say you have a array that keeps track of every number day of the year with an array
made up of 366 elements.(1 extra for leap year).

Is it possible to write a loop or something that when done cycling through the days array, that it resets back to monday to keep so that the output looks something like:

Monday:1
Tuesday:2
Wednesday:3
Thursday:4
Friday:5
Saturday:6
Sunday:7
Monday:8
Tuesday:9
ect all the way to 366

Answer

Just use the modulo operator (%):

for (int i = 1; i <= 366; i++) {
    System.out.format("%s:%d%n", days[(i - 1) % days.length], i);
}
Comments