Max Madill Max Madill - 1 month ago 10
Java Question

Java for loop to print each month of the year

The follow java code will print the numbers 1- 10 starting at 1. How can I use this same code structure to print out all of the months of the year only once so January, February, March, etc?

public class s {
public static void main(String[] args) {
for(int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}

Answer

If you want to do this the old fashion way and a little more hands on for learning arrays:

String[] months = new String[] { "January", "February", "March" };

for (int i = 0; i < months.length; i++) {
    System.out.println(months[i]);
}

Or to be a little more concise:

for (String month : months) {
    System.out.println(month);
}

You can learn more about arrays, and check out some tutorials in the documentation.