I am writing a simple game in which I use an Enum, CommandManager, to store information about the possible commands and what each one does. The main purposes of this Enum is to be able to print out a menu of available commands, as well as being used to check input and performing the action related to that input. My problem lies with that second use, where I am using a switch statement to determine what the user wants to do based on their input. I'm getting a compilation error when trying to use a property of an Enum (via a getter method) as a case label. The error message provided is that case expressions must be constant expressions. Given that the properties of CommandManager are declared to be final, am I right in thinking that properties of Enums simply cannot be used in switch statements? If this is the case, why?
Simplified version of the code included below in case it's an error on my end.
Method Code:
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; } } } Enum code:
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; } }
String commandfrom input, it would be nice to get the according enum value and then switch on the enum directly.enumto good use if you're switching against String values. If that's your goal, the have a number ofpublic static final Stringconstants. You'll be able to switch against them.enumclass, then it's usually a mistake toswitchon it because you can write constant-specific methods for the enum constants that in nearly every case provide a more object-oriented, robust, and more easily maintainable solution. Actually, in nearly every case your first reflex after writingswitchin your code should be to ask yourself "is there a way in which I can -not- switch?"