2016-04-07 19 views
1

我已經深入研究了這個問題,並找到了檢查字符串是否爲空的答案,但是在檢查我實例化的類是否爲空時沒有找到答案。這是一個由另一個類實例化的類,它保存所有房間的列表,就像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()方法。

我一直在爲此工作很多很多小時,目前我處於挫折的極限,任何幫助都將得到很大的讚賞。

+0

[Java的空檢查,而不是爲什麼使用==的可能的複製。等()](http://stackoverflow.com/questions/4501061/java-null-check-why-use-instead-of-equals) – Hypaethral

+0

退房http://stackoverflow.com/questions/4501061/java- null-check-why-use-instead-of-equals,我想你會發現它很有幫助。如果您在沒有實例時使用基於實例的等式方法,則會得到NullPointerException:「null.equals(null)」沒有意義,對吧?相反,使用==。 – Hypaethral

回答

1

表達式northExit.equals(null)(作爲一個例子)將不會按照您的想法工作。

考慮一下這種方式:northExit.位意味着提領該northExit參考準確地找到它指向。當它是null這樣的解除引用嘗試會給你例外,你看到。

正確的方法來檢查,如果值是null是使用參考平等的(a),沿着線:

if ((northExit != null) && (! northExit.equals(""))) ... 

的(a)教學時,I」我經常發現從學生那裏借了幾張五美元的筆記,並據此解釋。

根據參考等號==,它們不同,因爲它們實際上是不同的物理項目。在內容或價值的平等方面.equals(),它們是相同的。

然後我口袋裏的十塊錢,希望他們忘掉它的教訓,一個可愛的小補充我的收入結束:-)