23

Let's say I have an enum like so:

public enum Numbers {
    ONE("Uno "),
    TWO("Dos "),
    THREE("Tres ");
}

private final String spanishName;

Numbers(String spanishName) {
    this.spanishName = spanishName;
}

public String getSpanishName() {
    return spanishName;
}

Now I have a method that outputs a given variable.

public void output(String value) {
    printStream.print(value);
}

I want to use a for loop to output all the values in the enum. Something along the lines of this:

for(/*each element in the enum*/) {
    //output the corresponding spanish name
}

Ultimate I want the final output to be Uno Dos Tres. How can I do this using enums and a for loop?

1
  • @RaviThapliyal You won't find '.values()' under Enum in the JavaDocs. It's an implicit method for enum type. Commented May 21, 2013 at 16:33

3 Answers 3

45
for (Numbers n : Numbers.values()) {
   System.out.print(n.getSpanishName() + " ");
}
Sign up to request clarification or add additional context in comments.

Comments

7

Use this:

for (Numbers d : Numbers .values()) {
     System.out.println(d);
 }

Comments

5
for (Numbers num : Numbers.values()) {
  // do what you want
}

looks like duplicate: A 'for' loop to iterate over an enum in Java

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.