gpt4 book ai didi

关于为多个枚举构建HashMap的Java问题

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:05 24 4
gpt4 key购买 nike

我正在用 Java 制作一款 RPG 游戏作为学校作业。在游戏中,我接受用户输入,第一个单词是“命令词”,因此我创建一个枚举来将用户输入的字符串转换为枚举常量:

public enum CommandWord
{
GO("go"), QUIT("quit"), HELP("help"), BACK("back"), LOOK("look"), DROP("drop"), GRAB("grab"), USE("use"), UNKNOWN("?");

private String commandString;

/*
* Initialize with the corresponding command string.
* @param commandString the command string.
*/
CommandWord(String commandString) {
this.commandString = commandString;
}

public String toString()
{
return commandString;
}

有时第二个单词是“go”后面的方向,所以我有第二个枚举来表示具有更多常量的方向:

UP("up"), DOWN("down"), NORTH("north"), SOUTH("south"), EAST("east"), WEST("west"), UNKNOWN("unknown");

我正在尝试提出构建 HashMap 来存储字符串和相关枚举常量的最佳方法。对于命令词我有这个类:

public class CommandWords
{
// A mapping between a command word and the CommandWord
// that is associated with it
private HashMap<String, CommandWord> validCommands;
/**
* Constructor - initialise the command words.
*/
public CommandWords()
{
validCommands = new HashMap<>();
for (CommandWord command : CommandWord.values()) {
if(command != CommandWord.UNKNOWN) {
validCommands.put(command.toString(), command);
}
}
}

/**
* Searches the HashMap of valid commands for the supplied word.
* @param commandWord The word we're searching for.
* @return The CommandWord that is mapped to the supplied string commandWord,
* or UNKNOWN if it is not in valid command.
*/
public CommandWord getCommandWord(String commandWord)
{
CommandWord command = validCommands.get(commandWord);
if (command!= null) {
return command;
}
else {
return CommandWord.UNKNOWN;
}
}
}

然后我可以接受用户输入并搜索命令词,但我不能将其重用于方向、项目、字符等。我考虑过使用通用类,但我无法在其上调用 .values() 等方法,有没有一个好的方法可以做到这一点,以便我可以在不同的枚举上重用 CommandWords 类?

最佳答案

我们在 Enum 上有 valueOf(String) 方法,您不必构建该映射。

对于您的情况,您有一个值,并且知道您想要转换为哪种枚举类型。因此,只需使用:

CommandWord.valueOf("QUIT");
Items.valueOf("GEM");
etc..

枚举必须在编译时确定。

关于关于为多个枚举构建HashMap的Java问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53479671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com