我編碼一個遊戲,玩家必須輸入對話領域的東西,和Java有把它解釋爲一個動作。我有一個名爲GameEngine類在這裏我用一個開關:這裏使用NullPointerException異常與枚舉
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;
}
}
我的問題很簡單:當我輸入充電器,它的工作原理,但是當我輸入一個隨機單詞,不在列表中,我在該行
switch (commandWord)
在interpretCommand
獲得終端NullPointerException
。
我看不出有什麼錯我的代碼。如果有人能幫忙,謝謝。 請不要怪我,我是新手,我剛剛在幾個月前開始!
解決方案:在命令修改/添加這些行
public boolean isUnknown()
{
return (commandWord == null);
}
public CommandWord getCommandWord()
{
if(!isUnknown()){
return commandWord;
}
else return CommandWord.UNKNOWN;
}
在什麼線和表達也將NPE發生? – Confusion
在行「switch(commandWord)」 – Dany77
你沒有顯示你的Command類。如果您展示一個簡短但完整的示例來展示問題,這將非常有幫助。 –