我正在编写一个游戏,玩家必须在对话框字段中输入一些内容,而 java 必须将其解释为一个动作。我有一个名为 GameEngine 的类,我在其中使用开关:
public void interpretCommand(final String commandLine)
{
Command command = parser.getCommand(commandLine);
CommandWord commandWord = command.getCommandWord();
switch ( commandWord ) {
case UNKNOWN:
gui.println("Unknown command...");
return;
case LOAD:
load();
break;
}
}
此处使用的枚举位于 enumclass 中:
public enum CommandWord
{
LOAD("charger"),UNKNOWN("?");
private String commandWord;
}
最后是 CommandWords 类:
public class CommandWords
{
// a HashMap that holds all valid command words
private HashMap<String, CommandWord> validCommands;
public CommandWords()
{
validCommands = new HashMap<String, CommandWord>();
for(CommandWord command : CommandWord.values()) {
if(command != CommandWord.UNKNOWN){
validCommands.put(command.toString(), command);
}
}
}
/**
* @param commandWord the command word to look for in the valid commands
* @return the commandWord associated with the word typed
*/
public CommandWord getCommandWord(final String commandWord)
{
CommandWord command =validCommands.get(commandWord);
if(command !=null) {
return command;
}
else {
return CommandWord.UNKNOWN;
}
}
命令类:
public class Command
{
private CommandWord commandWord;
/**
* @param commandWord from enum class
*/
public Command(CommandWord commandWord)
{
this.commandWord = commandWord;
}
public CommandWord getCommandWord()
{
return commandWord;
}
}
我的问题很简单:当我输入充电器时,它可以工作,但是当我输入一个随机单词而不是在列表中时,我NullPointerException
在该行得到一个 in 终端
switch ( commandWord )
在解释命令中。
我看不出我的代码有什么问题。如果有人可以提供帮助,谢谢。请不要怪我,我是新手,几个月前才开始!
解决方案:在命令中修改/添加这些行
public boolean isUnknown()
{
return (commandWord == null);
}
public CommandWord getCommandWord()
{
if(!isUnknown()){
return commandWord;
}
else return CommandWord.UNKNOWN;
}