【发布时间】:2016-07-28 17:52:46
【问题描述】:
我对此进行了广泛的研究,并找到了检查字符串是否不为空的答案,但在检查我实例化的类是否为空时却没有找到答案。这是一个由另一个保存所有房间列表的类实例化的类,就像洞穴冒险游戏一样。代码如下:
public class Room
{
private String description;
private Room northExit;
private Room southExit;
private Room eastExit;
private Room westExit;
/**
* Create a room described "description". Initially, it has
* no exits. "description" is something like "a kitchen" or
* "an open court yard".
* @param description The room's description.
*/
public Room(String description)
{
this.description = description;
}
/**
* Define the exits of this room. Every direction either leads
* to another room or is null (no exit there).
* @param north The north exit.
* @param east The east east.
* @param south The south exit.
* @param west The west exit.
*/
public void setExits(Room north, Room east, Room south, Room west)
{
if(north != null)
northExit = north;
if(east != null)
eastExit = east;
if(south != null)
southExit = south;
if(west != null)
westExit = west;
}
/**
* @return The description of the room.
*/
public String getDescription()
{
return description;
}
public Room getExit(String direction)
{
if(direction.equals("north")) {
return northExit;
}
if(direction.equals("east")) {
return eastExit;
}
if(direction.equals("south")) {
return southExit;
}
if(direction.equals("west")) {
return westExit;
}
return null;
}
public String getExitString() {
if (!northExit.equals(null) && !northExit.equals(""))
return "north ";
if (!eastExit.equals(null) && !eastExit.equals(""))
return "east ";
if (!southExit.equals(null) && !southExit.equals(""))
return "south ";
if (!westExit.equals(null) && !westExit.equals(""))
return "west ";
else {
System.out.println("There are no doors!");
return null;
}
}
}
当它到达 getExitString() 方法时,我最终得到了 NullPointerException。
我已经为此工作了很多小时,目前我的挫败感已经到了极限,我们将不胜感激。
【问题讨论】:
-
查看stackoverflow.com/questions/4501061/…,我想你会发现它很有帮助。如果在没有实例的情况下使用基于实例的相等方法,您将得到 NullPointerException: "null.equals(null)" 没有意义,对吧?请改用 ==。