Is it possible to have an enumeration class with enumerations of two or more words?

I need to choose from several genres for books, and I thought about using listings for this, but there are several genres made up of two or more words, such as "Medicine, health and fitness", "Art and photography", Science fiction "etc. .d.

public enum Genero { Action, Comedy, Drama, Computers, Novel, Science Fiction } 

But I got a syntax error for Science Fiction. I tried putting it with double quotes and simple gags, but none of them worked. This listing will be used as an attribute for the Book class.

+7
source share
3 answers

No, It is Immpossible. Enum names must be valid Java identifiers - this means there are no spaces. A common convention is to declare enumeration names in all uppercase characters and single words using underscores, for example:

 public enum Genero { ACTION, COMEDY, DRAMA, COMPUTERS, NOVEL, SCIENCE_FICTION } 
+14
source

It's impossible. However, you can use the underscore ( Science_Fiction ) in the title. You can also override the toString method to return everything you want (since, as you see, you are going to be read by a person for your listings):

 public enum Genero { ACTION("Action"), COMEDY("Comedy"), DRAMA("Drama"), COMPUTERS("Computers"), NOVEL("Novel"), SCIENCE_FICTION("Science Fiction"); private final String toString; private Genero(String toString) { this.toString = toString; } public String toString(){ return toString; } } 
+5
source

This might be what you want:

 static private enum EnumExample { R("Sample emun with spaces"), G("Science Fiction"); final private String value; EnumExample(String s) { value = s; } } System.out.println(EnumExample.G.value); System.out.println(EnumExample.valueOf("G").value); Science Fiction Science Fiction 
0
source

All Articles