Java 如何在没有变量的情况下从枚举中获取值
我有以下枚举器:Java 如何在没有变量的情况下从枚举中获取值,java,enums,Java,Enums,我有以下枚举器: public enum UserChoice { QUIT, LIST_BOOKS, CHECKOUT_BOOK, RETURN_BOOK, LIST_MOVIES, CHECKOUT_MOVIE, RETURN_MOVIE, USER_INFORMATION } 我想在switch语句中使用它,它将int作为参数。但是,我需要获取枚举的int值,因此我要执行以下操作: try { int option = Reader.getUserOption()
public enum UserChoice {
QUIT, LIST_BOOKS, CHECKOUT_BOOK, RETURN_BOOK, LIST_MOVIES,
CHECKOUT_MOVIE, RETURN_MOVIE, USER_INFORMATION
}
我想在switch语句中使用它,它将int作为参数。但是,我需要获取枚举的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转换为枚举值,或者谁可以使用枚举实现这一点。最后,我的重点是为每个案例指定枚举器的名称,这样我就可以清楚地了解每个案例在做什么,因为以前我是使用int值来做的。UserChoice.values()[option]
应该这样做。您可以分别确定选项>=0
和选项
请注意,有很多资源反对使用或存储ordinal
,因为如果添加、删除或重新排序枚举值,这些数字都会发生变化。如果数字是类似于枚举的返回值的固有部分,则电影应始终解析为选项6—您可能希望将其作为枚举常量的构造函数参数和属性,并通过单独的映射提供查找。UserChoice.values()。您可以分别确定选项>=0
和选项
请注意,有很多资源反对使用或存储ordinal
,因为如果添加、删除或重新排序枚举值,这些数字都会发生变化。如果该数字是类似于枚举的返回值的固有部分,则电影应始终解析为选项6—您可能希望将其作为枚举常量的构造函数参数和属性,并通过单独的映射提供查找。为无效选择创建一个额外的枚举值并使用该值。但除此之外,您还应该将用户输入与枚举的顺序(以及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());
}
}
公共静态枚举用户选择{
/*
*建立枚举值(语义操作)之间的映射
*和用户的输入。这可以适应用户的任何形式
*输入采用顺序值,并与顺序值解耦。它都在
*这里有一个地方,这里有一个变化,其他地方不需要变化。
*/
退出(0),
图书目录(1),
结帐簿(2),
还书(3),
电影列表(4),
电影(5),
返回电影(6),
用户信息(7),
无效的_选择(整数.MIN_值);
/*
*映射及其初始化使用Java8中的新特性
*/
私有静态最终映射valueMap=Arrays.stream(UserChoice.values()).collect(Collectors.toMap(UserChoice::getValue,Function.identity());
/*
*将用户输入(本例中为int)转换为相应的
*基于上述映射的枚举值。
*/
来自UserInput的公共静态UserChoice(int输入){
返回可选的.ofNullable(valueMap.get(input)).orElse(无效的_选项);
}
/*
*每枚举值和方法
*/
私有最终int用户值;
私有UserChoice(int userValue){this.userValue=userValue;}
public int getValue(){返回this.userValue;}
}
/*
*简单测试
*/
公共静态void main(字符串args[])引发异常
{
对于(int i=0;i为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());
}
}
公共静态枚举用户选择{
/*
*建立枚举值(语义操作)之间的映射
*和用户的输入。这可以适应用户的任何形式
*输入采用顺序值,并与顺序值解耦。它都在
*这里有一个地方,这里有一个变化,其他地方不需要变化。
*/
退出(0),
图书目录(1),
结帐簿(2),
还书(3),
电影列表(4),
电影(5),
返回电影(6),
用户信息(7),
无效的_选择(整数.MIN_值);
/*
*映射及其初始化使用Java8中的新特性
*/
私有静态最终映射valueMap=Arrays.stream(UserChoice.values()).collect(Collectors.toMap(UserChoice::getValue,Function.identity());
/*
*将用户输入(本例中为int)转换为相应的
*基于上述映射的枚举值。
*/
来自UserInput的公共静态UserChoice(int输入){
返回可选的.ofNullable(valueMap.get(input)).orElse(无效的_选项);
}
/*
*每枚举值和方法
*/
私有最终int用户值;
私有UserChoice(int userValue){this.userValue=userValue;}
public int getValue(){返回this.userValue;}
}
/*
*简单测试
*/
公共静态void main(字符串args[])引发异常
{
对于(int i=0;i请尝试UserChoice.values()[option]
其中选项从0开始,而option请尝试UserChoice.values()[option]
其中选项从0开始,如果Reader.getUserOption()
从UserChoice枚举器返回一个选项,则不需要强制转换
例子:
当然,你需要在试一试中完成开关盒
编辑:
如果方法getUserOption
返回一个int,并且该int是枚举数中选项的顺序表示形式:
退出,用户信息
0
然后这样做:
switch (UserChoice.values()[Reader.getUserOption()]) {
如果Reader.getUserOption()
从UserChoice枚举器
返回一个选项,则不需要强制转换
例子:
您需要进行switc
try {
int option = Reader.getUserOption();
} catch (InputMismatchException ex) {
option = 8;
}
switch (UserChoice.values()[option]) {
case QUIT:
break;
case LIST_BOOKS:
Printer.printBooks(library);
break;
case CHECKOUT_BOOK:
// code
break;
case RETURN_BOOK:
// code
break;
case LIST_MOVIES:
Printer.printMovies(library);
break;
case CHECKOUT_MOVIE:
// code
break;
case RETURN_MOVIE:
// code
break;
case USER_INFORMATION:
System.out.println(currentUser);
break;
default:
Printer.printInvalidOptionMessage();
break;
}