很抱歉,如果这是一个愚蠢的问题,但我对java很新。基本上我们正在学习java类中的接口和映射。我创建了一个非常简单的接口,并且还创建了实现该接口的其他类。在我作为主要演员的班级中,我正在创建一个地图,我已经创建了这些实例,如下所示。我得到了NPE而且我不确定为什么。
private Scanner input;
private Map<String, Command> map;
//~ Constructors ..........................................................
// ----------------------------------------------------------
/**
* Creates a new Rocket object that reads commands
* from a predefined URL (the URL is in the lab assignment).
*/
public Rocket()
{
this(IOHelper.createScannerForURL(
"http://courses.cs.vt.edu/~cs1114/Fall2012/rocket-commands.txt")
);
}
// ----------------------------------------------------------
/**
* Creates a new Rocket object that reads commands
* from the given scanner.
* @param scanner The scanner to read commands from.
*/
public Rocket(Scanner scanner)
{
input = scanner;
map = new HashMap<String, Command>();
ForwardCommand forward = new ForwardCommand(this);
map.put("forward", forward);
LeftCommand left = new LeftCommand(this);
map.put("left", left);
RightCommand right = new RightCommand(this);
map.put("right", right);
}
//~ Methods ...............................................................
// ----------------------------------------------------------
/**
* Reads one word from the scanner (if there is any), and executes
* the corresponding command. If the scanner has no words remaining,
* then nothing happens.
*/
public void act()
{
if (input.hasNext())
{
String word = input.next();
map.get(word).execute();
}
}
}
错误出现在map map.get(word).execute();
上我确定这是显而易见的事情,但我对编码很陌生,所以任何帮助都会受到赞赏!