我有以下枚举器:
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());
}
}