簡體   English   中英

空指針異常及其解決方法

[英]Null Pointer Exception & how to overcome it

在為我的代碼運行公共測試時,在相似的行上收到了2個錯誤。 錯誤是:

空指針異常錯誤及其出現的行是其中包含getCurrentLocation&getName的錯誤。

assertEquals(“最初,Parrade處於趣味之火”,“ 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;
}

任何想法如何解決這個問題?

如果這是導致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;

意味着您已經聲明了該變量,但是尚未初始化它。 用類似下面的命令初始化它:

parrade = new Parade();

之所以得到空指針,是因為從未設置location或name的值。 聲明所有實例變量時,它們最初都是null,因此,如果在實例化它們之前嘗試使用它們,它將拋出null指針異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM