簡體   English   中英

當我創建一個新類的實例時,為什么會出現java.lang.NullPointerException?

[英]Why do I get a java.lang.NullPointerException when I make a new Instance of a my class?

我需要創建這個類的實例,但是當我嘗試時,我得到一個NullPointerException。 你能告訴我為什么以及如何解決這個問題,我還是很陌生。

public class NewTryPoints {

private int[] pointX;
private int[] pointY;
private static final int topix = 5;

public NewTryPoints(){
    setX();
    setY();
    }

public void setX(){

    pointX[0] = 1;
    pointX[1] = (int)Math.random() * ( 50 - 1 ) * topix;
    pointX[2] = 2 + (int)(Math.random() * ((50 - 2) + 1)) * topix;
};

public void setY(){

    pointY[0] = 1 * topix;
    pointY[1] = 2 + (int)(Math.random() * ((50 - 2) + 1)) * topix;
    pointY[2] = 1 * topix;

};

public int[] getpointX() { return pointX; };
public int[] getpointY() { return pointY; };

}

其他課程

public class Main {

public static void main(String[] args) {
NewTryPoints points = new NewTryPoints();   

  }

}

您正在使用引用pointXpointY而不分配它們的內存,因此它們為null並引發NullPointerException。 你應該先做..

public NewTryPoints(){
    pointX = new int[3];
    pointY = new int[3];
    setX();
    setY();
}

您尚未初始化陣列。

在調用setx和sety之前在構造函數中添加它。

pointX = new int[3];
pointY = new int[3];

您根本不初始化數組:

private int[] pointX;
private int[] pointY;

嘗試訪問set-method會導致null,因為它們還沒有包含對數組對象的引用!

在Java中使用它之前,必須初始化該數組。 請在構造函數中的setXsetY方法中設置值之前初始化數組

public NewTryPoints(){
    //initializing the arrays
    pointX = new int[3]; 
    pointY = new int[3];
    setX();
    setY();
    }

希望這可以幫助!

在構造函數中,您調用setX()setY() ,然后使用值填充數組。 問題是你沒有初始化這些數組:

pointX = new int[5]; // 5 is just for the example
pointY = new int[5];

您尚未初始化對數組的引用。 這意味着

private int[] pointX;

是相同的

private int[] pointX = null;

所以當你這樣做

pointX[0] = ...

它拋出一個NullPointerException。

你可以看到這種方法的一種方法是在調試器中查看它。

很可能你打算寫

private int[] pointX = new int[3];

暫無
暫無

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

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