for loops and enum

There are 12 months in a year.

I need to define an enumeration (enum) of each of the month. I also need to utilize a for loop to display each month.

The part im stuck on is that we need to format our output to look like this:

Month 1: JAN

Month 2: FEB

...

Month 12: DEC

So far, this is my code:

enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}
for (Month m : m.values())
{
   System.out.println(m);
}

Would I need to do a nested for-loop in order to have "Month (# of Month) : " show?

for ( int i = 1; i <= 12; i++)
{
    System.out.println("Month" + i + ": ");
    for (Month m : m.values())
    { 
       System.out.println(m);
    }
}

Sorry if this may not compile (i'm not on my computer with my IDE) But I know if i do that nested loop, its going to list ALL the values of the enum for each iteration of the outside loop. I tried to replace the inside statement to say "System.out.println(m.value(i));" but that doesn't work because the compiler states that the method doesnt work on int types. So what can I do to make this work?

Answers


Given your Month enum you can access ordinal() and name() to get your output. Something like,

for (Month m : Month.values()) {
    System.out.printf("Month %d: %s%n", m.ordinal() + 1, m.name());
}

Need Your Help

Intellisense quick fix

intellisense visual-studio-code

I'm using a machine with installed Arch Linux and Windows 10. Both of them have Visual Studio Code installed. But, on Arch Linux every unknown definitions can be easily picked up trhough CTRL+.. On

set field to hidden if respective link is not clicked

php jquery html ajax

I load additional info when a user clicks a link and there is a multi-select drop-down holds[] that appears.