有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java空指针异常&如何克服

在为我的代码运行公共测试时,我在类似的行中收到了两个错误。错误是:

空指针异常错误,它们出现的行是带有getCurrentLocation&;把名字放进去

assertEquals("Initially, Parrade is at Fun Fire", "Fun Fire", parrade.getCurrentLocation().getName());

parrade.move();

我的构造函数以及getCurrentLocation&;的完整代码;getName如下所示:

代码:

public abstract class Ride {
private String name;
private int duration;
private int batchSize;
private ArrayList<Amuser> currentAmusers;
private int ridesToMaintain;
private FunRide location;

public Ride() {
    this.name = "Serpent";
    this.duration = 5;
    this.batchSize = 20;
    this.ridesToMaintain = 10;
    this.currentAmusers = new ArrayList<Amuser>();
}

public Ride(String name, int duration, int batchSize) {
    this.name = name;
    this.duration = duration;
    this.batchSize = batchSize;
    this.ridesToMaintain = 10;
    this.currentAmusers = new ArrayList<Amuser>();
}

public FunRide getCurrentLocation() {
    return this.location;
}

你知道怎么解决这个问题吗


共 (2) 个答案

  1. # 1 楼答案

    获取空指针的原因是从未设置位置或名称的值。当您声明所有实例变量时,它们最初都是空的,因此如果您在实例化它们之前尝试使用它们,它将抛出空指针异常

  2. # 2 楼答案

    如果这是导致NullPointerException

    assertEquals("Initially, Parrade is at Fun Fire", "Fun Fire", parrade
       .getCurrentLocation().getName());
    

    然后parradeparrade.getCurrentLocation()等于nullparrade.getCurrentLocation().getName()抛出一个(后者似乎不太可能)。但是,由于这个变量在你发布的代码中不存在,恐怕我们无法为你提供更多帮助

    你肯定已经有类似的东西了(假设parrade是罪魁祸首)

    private Parade parrade = null;
    

    或者

    private Parade parrade;
    

    意思是你已经declared这个变量,但你还没有初始化它。用如下方式初始化它:

    parrade = new Parade();