John White John White - 6 months ago 25
Java Question

Java: Can one get printf to show an enum's name?

I notice that println() does this, but I cannot get it to work in printf().

In the following snippet, the first two println's give RED and BLUE, then the printf crashes.

class Jim {
public enum Colours {BLUE, RED}
static Colours xx = Colours.RED;
public static void main(String[] args) {
Colours fred = Colours.BLUE;
System.out.println(xx);
System.out.println(fred);
System.out.printf("%d, %d\n", fred, xx);
}

Answer

%d format specifiers are not compatible with enum types unless used against the ordinal value. To invoke the enum's toString method (which uses the name field) you can use %s instead

System.out.printf("%s, %s%n", fred, xx);

Read: Enum

Comments