【问题标题】:Null Pointer Exception & how to overcome it空指针异常以及如何克服它
【发布时间】:2014-04-27 16:46:39
【问题描述】:

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

空指针异常错误和它们出现的行是其中包含 getCurrentLocation 和 getName 的行。

assertEquals("最初,Parrade 在 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;
}

知道如何解决这个问题吗?

【问题讨论】:

标签: java exception pointers null nullpointerexception


【解决方案1】:

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

【讨论】:

    【解决方案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();
    

    【讨论】:

    • @Sandeep:这个答案对你有帮助吗?
    猜你喜欢
    • 2014-01-06
    • 2018-03-15
    • 2016-01-06
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多