我已经对此进行了广泛的研究,并找到了检查字符串是否为空的答案,但是在检查我实例化的类是否为空时却没有。这是一个由另一个类实例化的类,它保存所有房间的列表,就像Cave Adventure游戏一样。这是代码:
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。
我已经花了很多时间研究这个问题而且我目前处于挫折的极限,任何帮助都会非常感激。
答案 0 :(得分:1)
表达式northExit.equals(null)
(作为一个示例)将无法正常工作。
以这种方式思考:northExit.
位意味着northExit
引用的解除引用,以找到它指向的内容。如果null
null
这样的取消引用会给您提供您所看到的例外情况。
检查值是否为if ((northExit != null) && (! northExit.equals(""))) ...
的正确方法是使用引用相等(a),如下所示:
==
(a)在教学时,我经常发现从学生那里借了几张五美元的笔记,并对其进行解释。
就参考平等.equals()
而言,它们之间存在差异,因为它们实际上是不同的物理项目。在内容或价值平等abstract class Edge2D[T : Point2DInterface] {
val p1: T
val p2: T
def length(): Double = {
implicitly[Point2DInterface[T]].Sub(p1, p2)
}
}
trait Point2DInterface[T] {
def Sub(first: T, second: T): Double
}
方面,它们是相同的。
然后我掏了十块钱,希望他们在课程结束时忘掉它,这是我收入的一个很好的补充: - )