简体   繁体   中英

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

I need to make a Instance of this class but when I try I get a NullPointerException. Can you tell me why and how to fix, I'm still pretty new at this.

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; };

}

other class

public class Main {

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

  }

}

You are using references pointX and pointY without assigning them memory, hence they are null and a NullPointerException is raised. You should first do ..

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

You have not initialized the array.

add this in the constructor before the calls to setx and sety.

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

You do not initialize the arrays at all:

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

Trying to access either in the set-method results in null, as they do not contain a reference to an array object yet!

You have to initialize the array before you use it in Java. Please initialize the arrays before you set the values in setX and setY methods in the constructor

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

Hope this helps!

In your constructor you are calling setX() and setY() which in turn fill your arrays with values. Problem is you did not initialize these arrays:

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

You haven't initialized your references to arrays. This means that

private int[] pointX;

is the same as

private int[] pointX = null;

so when you do

pointX[0] = ...

it throws an NullPointerException.

One way you could have seen this is by looking at this in your debugger.

Most likely you intended to write

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM