我正在编写一个简单的游戏,其中使用枚举CommandManager
来存储有关可能的命令以及每个命令的作用的信息。该枚举的主要目的是能够打印出可用命令的菜单,以及用于检查输入并执行与该输入相关的操作。我的问题在于第二次使用,我使用 switch 语句来根据用户的输入确定用户想要执行的操作。当我尝试使用 Enum 的属性(通过 getter 方法)作为 case 标签时,出现编译错误。提供的错误消息是 case 表达式必须是常量表达式
。鉴于 CommandManager 的属性被声明为最终属性,我是否认为枚举的属性根本不能在 switch 语句中使用?如果是这样,为什么?
下面包含代码的简化版本,以防我这边出现错误。
方法代码:
void interpretInput() {
String command = input.getInput();
if (command.length() == 2) {
switch (command) {
case CommandManager.MAINMENU.getCommand(): goToMainMenu();
break;
case CommandManager.NEWGAME.getCommand(): startNewGame();
break;
case CommandManager.LISTGAMES.getCommand(): listSavedGames();
break;
case CommandManager.EXITGAME.getCommand(): exitGame();
break;
case CommandManager.HELPMENU.getCommand(): listAllCommands();
break;
}
}
}
枚举代码:
public enum CommandManager {
NEWGAME("!n", "New game"),
MAINMENU("!m", "Go to main menu"),
EXITGAME("!q", "Exit Battleships"),
LISTGAMES("!g", "List saved games"),
HELPMENU("!h", "Open help menu"),
LOADGAME("!l", "Load a new game"),
SAVEGAME("!s", "Save current game");
private final String command;
private final String menuOption;
CommandManager(String aCommand, String anOption) {
command = aCommand;
menuOption = anOption;
}
String getCommand() {
return command;
}
String getMenuOption() {
return menuOption;
}
}
最佳答案
Am I right in thinking that properties of Enums simply cannot be used in switch statements?
你是。
If this is the case, why?
因为 switch 语句的“标签”需要是编译时常量,而 enum
的属性不符合条件。
它们需要成为编译时常量的原因是编译器需要检查开关标签是否不同。它不能允许这样的事情
switch (someValue) {
case A.method(): doA();
case B.method(): doB();
}
其中 A.method()
和 B.method()
结果具有相同的值。如果 case 表达式不是编译时常量表达式,则编译器无法检测到问题。 (方法调用永远不是编译时常量表达式。)
关于java - 为什么 switch case 语句无法使用 Enum 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39933520/