【问题标题】:Check if not null Bluej (Java) not working检查是否不为空 Bluej (Java) 不工作
【发布时间】: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。

我已经为此工作了很多小时,目前我的挫败感已经到了极限,我们将不胜感激。

【问题讨论】:

标签: java null bluej


【解决方案1】:

表达式northExit.equals(null)(作为一个例子)不会像你想象的那样工作。

这样想:northExit. 位意味着对northExit 引用的取消引用,以找到它所指向的确切内容。当它是 null 时,这样的取消引用尝试会给你你所看到的异常。

检查一个值是否为null 的正确方法是使用引用相等(a),如下:

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

(a)在教学中,我经常发现从学生那里借了几张五美元的钞票,并这样解释。

在引用相等== 方面,它们是不同的,因为它们实际上是不同的物理项目。就内容或价值相等.equals()而言,它们是相同的。

然后我把十块钱装在口袋里,希望他们在课程结束时忘记它,这是我收入的一个不错的小补充:-)

【讨论】:

    猜你喜欢
    • 2011-09-21
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2021-09-12
    相关资源
    最近更新 更多