Reputation: 21
I'm coding a game where the player has to type something in the dialog field, and java has to interpret it as an action. I have a class named GameEngine where i use a switch :
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;
}
}
Enums used here are in an enumclass :
public enum CommandWord
{
LOAD("charger"),UNKNOWN("?");
private String commandWord;
}
and finally, the CommandWords class :
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;
}
}
the Command class :
public class Command
{
private CommandWord commandWord;
/**
* @param commandWord from enum class
*/
public Command(CommandWord commandWord)
{
this.commandWord = commandWord;
}
public CommandWord getCommandWord()
{
return commandWord;
}
}
My problem is very simple: when I type charger, it works, but when I type a random word, not in the list, I get a NullPointerException
in terminal at the line
switch ( commandWord )
in interpretCommand.
I can't see what's wrong with my code. If someone could help, thank you. Please don't blame me, I'm a novice, I just started a few months ago!
Solution : in command modify/add these lines
public boolean isUnknown()
{
return (commandWord == null);
}
public CommandWord getCommandWord()
{
if(!isUnknown()){
return commandWord;
}
else return CommandWord.UNKNOWN;
}
Upvotes: 0
Views: 4185
Reputation: 43798
There is only one thing that can be null at this line and that is commandWord
. So your method call command.getCommandWord()
returns null.
EDIT: With the information you have provided now, this means that the parser gives back a Command
object which has no commandWord set.
Upvotes: 2