是否可以有一个枚举类,其中包含两个或多个单词的枚举



我必须从几种类型的书籍中进行选择,我曾考虑使用枚举,但也有几种类型的书是由两个或多个单词组成的,如"医学、健康与健身"、"艺术与摄影"、"科幻"等。

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

但我在《科幻小说》中出现了语法错误。我试着用双引号和简单的quutes来表达,但都不起作用。此枚举将用作Book类的属性。

不,这是不可能的。枚举名称必须是有效的Java标识符,也就是说,不能有空格。通常的惯例是用所有大写字符声明枚举名称,并使用下划线分隔单词,如下所示:

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

这是不可能的。但是,也可以在名称中使用下划线(Science_Fiction)。您也可以覆盖toString方法,以返回您想要的任何内容(因为它看起来是为您的枚举寻找一个人类可读的名称):

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;
    }
}

这可能是您想要的:

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

最新更新