java - 如何在没有变量的情况下从枚举中获取值

标签 java enums

<分区>

我有以下枚举器:

public enum UserChoice {
    QUIT, LIST_BOOKS, CHECKOUT_BOOK, RETURN_BOOK, LIST_MOVIES,
    CHECKOUT_MOVIE, RETURN_MOVIE, USER_INFORMATION
}

我想在将 int 作为参数的 switch 语句中使用它。但是,我需要获取枚举的 int 值,所以我这样做:

try {
    int option = Reader.getUserOption();
} catch (InputMismatchException ex) {
    option = 8;
}

switch (option) {
    case UserChoice.QUIT.ordinal():
        break;
    case UserChoice.LIST_BOOKS.ordinal():
         Printer.printBooks(library);
         break;
    case UserChoice.CHECKOUT_BOOK.ordinal():
         // code
         break;
    case UserChoice.RETURN_BOOK.ordinal():
         // code
         break;
    case UserChoice.LIST_MOVIES.ordinal():
         Printer.printMovies(library);
         break;
    case UserChoice.CHECKOUT_MOVIE.ordinal():
         // code
         break;
    case UserChoice.RETURN_MOVIE.ordinal():
         // code
         break;
    case UserChoice.USER_INFORMATION.ordinal():
         System.out.println(currentUser);
         break;
    default:
         Printer.printInvalidOptionMessage();
         break;
    }

有什么方法可以将 int 转换为枚举值,或者谁可以使用枚举来实现此目的。最后,我的观点是每个案例都有 enumerator 的名称,这样我就可以清楚地了解每个案例在做什么,因为之前我是使用 int 值来做的。

最佳答案

INVALID_CHOICE 创建一个额外的枚举值并使用它。但更重要的是,您应该将用户输入与枚举的排序(和 ordinal 值)完全分离。

这是一个如何做到这一点的例子。

public static enum UserChoice {
    /*
     * Establish the mapping between the enum value (the semantic action)
     * and the user's input.  This can be adapted to whatever form the user
     * input takes and is decoupled from the ordinal values.  It's all in 
     * one place here and a change here does not need a change anywhere else.
     */
    QUIT            ( 0), 
    LIST_BOOKS      ( 1), 
    CHECKOUT_BOOK   ( 2), 
    RETURN_BOOK     ( 3), 
    LIST_MOVIES     ( 4),
    CHECKOUT_MOVIE  ( 5), 
    RETURN_MOVIE    ( 6), 
    USER_INFORMATION( 7),
    INVALID_CHOICE  (Integer.MIN_VALUE);

    /*
     * The mapping, and its initialization, using the new features in Java 8
     */
    private static final Map<Integer,UserChoice> valueMap = Arrays.stream(UserChoice.values()).collect(Collectors.toMap(UserChoice::getValue, Function.identity()));

    /*
     * A method to convert from user input (int in this case) to the corresponding
     * enum value based on the mapping above.
     */
    public static UserChoice fromUserInput(int input) {
        return Optional.ofNullable(valueMap.get(input)).orElse(INVALID_CHOICE);
    }

    /*
     * Per-enum value and method
     */
    private final int userValue;
    private UserChoice(int userValue) { this.userValue = userValue; }
    public int getValue() { return this.userValue; }
}

/*
 * Simple test
 */
public static void main(String args[]) throws Exception 
{
    for (int i=0; i<10; i++)
    {
        UserChoice c = UserChoice.fromUserInput(i);
        System.out.printf("Input %d enum is %s\n", i, c.toString());
    }
}   

关于java - 如何在没有变量的情况下从枚举中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36091672/

相关文章:

java - 如何正确关闭 javafx Alerts/fileChooser 等

java - 更改父目录和子目录中的文件名

java - 需要将 AssetInputStream 转换为 FileInputStream

java - java中的枚举值列表

java - 我想要做到这一点,所以如果我点击 btnNewButton 它会更改 textArea 上的文本

java - JGraph AWT EventQueue 绘制异常(使用多线程)

c++ - const 枚举或其他

C Language : trouble using enumerated variable and type definited in main. c文件在另一个文件里面

java - 为什么 EnumMap 构造函数需要类参数?

vb.net - 枚举成员列表以数字开头