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?
Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. You can iterate the contents of an enumeration using for loop, using forEach loop and, using java.
CA1069: Enums should not have duplicate values (code analysis) - .
The java. lang. Enum. clone() method guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.
for (Numbers n : Numbers.values()) {
System.out.print(n.getSpanishName() + " ");
}
Use this:
for (Numbers d : Numbers .values()) {
System.out.println(d);
}
for (Numbers num : Numbers.values()) {
// do what you want
}
looks like duplicate: A 'for' loop to iterate over an enum in Java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With