我正在用Java创建一个命令行游戏。有一个游戏课堂和课堂课程的基本前提:进入正确的房间,游戏结束。HashMap返回null
从每个房间的用户可以通过移动方向:
public void move (String direction) {
Room nextRoom = currentLocation.getNeighbor(direction); //this is the problem, always nil
if (nextRoom == null){
msg = "You can't go in that direction";
}else{
currentLocation = nextRoom;
msg = currentLocation.getLongDescription();
}
}
的问题是,这种.getNeighbor方法返回nil,所以这个问题是我的getNeighbor方法我的房类中或可能与我怎么创造房间。这里是客房类中我getNeighbor方法:
public Room getNeighbor(String rDirection){
Room next = map.get(rDirection);
return next;
}
这需要我的字符串,并期待在我创建,看看他们是朝着这一方向键一个房间一个HashMap的地图。恐怕这个问题是我如何创建我的房间的方向的HashMap:
在我的房间类别:
private HashMap<String , Room> map = new HashMap<String , Room>();
我有一个创建地图的方法在我的房间类,我初始化我比赛的时候调用。下面是增加方向的方法,然后我在我的游戏类我打电话:
// Room Class Method
public void addNeighbor(String rDirection, Room r){
map.put(rDirection, r);
}
// Game Class - Initializing the Rooms
kitchen.addNeighbor("east", foyer);
kitchen.addNeighbor("north", library);
我无法找到一个邻居到我的房间,从任何一个房间我看看。错误发生在注释行上,但我认为这是我的房间类方法,或者我创建HashMap的方式(我以前从未使用过)。无论如何,我想知道是否有人能够帮助指出我似乎错过了什么,以及为什么我的房间在我的地图中没有任何邻居。万分感谢。
为了更好地帮助您:1)发布[SSCCE](http://sscce.org/)。 2)提出问题。 –