我已經深入研究了這個問題,並找到了檢查字符串是否爲空的答案,但是在檢查我實例化的類是否爲空時沒有找到答案。這是一個由另一個類實例化的類,它保存所有房間的列表,就像Cave Adventure遊戲一樣。下面是代碼:檢查是否爲空Bluej(Java)不工作
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;
}
}
}
我最終得到一個NullPointerException當它達到getExitString()方法。
我一直在爲此工作很多很多小時,目前我處於挫折的極限,任何幫助都將得到很大的讚賞。
[Java的空檢查,而不是爲什麼使用==的可能的複製。等()](http://stackoverflow.com/questions/4501061/java-null-check-why-use-instead-of-equals) – Hypaethral
退房http://stackoverflow.com/questions/4501061/java- null-check-why-use-instead-of-equals,我想你會發現它很有幫助。如果您在沒有實例時使用基於實例的等式方法,則會得到NullPointerException:「null.equals(null)」沒有意義,對吧?相反,使用==。 – Hypaethral