For a loop to print the enumeration indices but not the values

public enum Months{
JANUARY("first"), FEBRUARY("second"), MARCH("third"), APRIL("fourth"), MAY("fifth"), JUNE("sixth"), JULY("seventh"), 
AUGUST("eigth"), SEPTEMBER("ninth"), OCTOBER("tenth"), NOVEMBER("eleventh"), DECEMBER("twelfth");

private String name;
// value in parentheses after elements
Months(String name){
    this.name = name;
}
public String getName(){
    return name;
}
public String toString(){
    return name;
}

      

this is my listing

public class Test {
   public static void main(String [] args){
   for(Months m : Months.values()){
      System.out.println(m);
   } 

      

This is my main method. But this for the loop calls the toString method and prints the values โ€‹โ€‹of the indices, that is, the first, second, etc. Is there a way that I can loop through and print the indices i.e. JANUARY, FEBRUARY, etc.?

+3


source to share


2 answers


All you have to do is change System.out.println(m);

to System.out.println(m.name())

:



public static void main(String[] args) {
    for (Months m : Months.values()) {
        System.out.println(m.name()); // Change is in this line.
    }
}

      

0


source


All elements enum

provide a method name()

that will give you the id used to define the element eg. Month.JANUARY.name()

will be "JANUARY"

.



+7


source







All Articles