This is a fine exercise. Just for the bigger picture, it’s nothing one would use for production code in real life.
There are basically two ways. Both will work fine.
- Use two nested loops. The outer loop will iterate over the months of the year. The inner loop will iterate over the days of the month.
- Use one loop over the days of the year.
In both cases you will also need to keep track of the day of the week throughout. Edit again: If you know about enum
in Java, use an enum for the months and another enum for the days of the week. If you don’t know enums, as Andreas has already mentioned, use int
for each of month, day of month and day of week. Use the int
s for looking up the strings in your arrays. Because an int
can be incremented and because array indices are int
s.
Further edit: To answer the question in your title, assuming that you are using an int
index into dayOfTheWeek
to represent the next day of the week. There are several ways to increment for each day printed. I find this way natural and simple:
dayOfWeekIdx++;
if (dayOfWeekIdx == dayOfTheWeek.length) { // Overflown
dayOfTheWeek = 0; // Reset
}
Some prefer this much shorter way:
dayOfTheWeek = (dayOfTheWeek + 1) % dayOfTheWeek.length;
The modulo operator, %
gives you the remainder after dividing. So when dayOfTheWeek
overflows, that is, becomes 7, the division is 7 divided by 7, which is 1 with a remainder of 0, so dayOfTheWeek
gets reset to 0.
In the version with one loop over all the days of the years you may do similarly to four-line solution for day of week, only inside the if
statement add a line for incrementing the month index.
So what would one use for production code? This is mostly for other readers. One would use LocalDate
and also DateTimeFormatter
, both from java.time, the modern Java date and time API. No one in their right mind would use Date
nor Calendar
, the classes that you mentioned in the question, since they are both poorly designed and long outdated.