Tyler McAnally Tyler McAnally - 2 months ago 10
Java Question

Adding object to array and getting NullPointerException

I have a class ConvexHull which I have to implement for my class. One of the instance variables is an array that holds the object Points.

private Points[] points;


When I go to add a Point to the array in the constructor, I'm given a NullPointerException.

public ConvexHull(int n) throws IllegalArgumentException
{
if (n < 1)
throw new IllegalArgumentException();
else {

Random rand = new Random();

for (int i=0; i<n; i++)
{
int x = rand.nextInt(101)-50;
int y = rand.nextInt(101)-50;
Point p = new Point(x,y);
this.points[i] = p; // NullPointerException is thrown.
this.numPoints = points.length;
}
}
}


Basically, I have no idea why this isn't working and need some help.

Answer

Please allocate memory for

private Points[] points;

like this..

public ConvexHull(int n) throws IllegalArgumentException 
{

    if (n < 1)
        throw new IllegalArgumentException();
    else {
        points=new Points[n];  //this is the line that is added

        Random rand = new Random();

        for (int i=0; i<n; i++)
        {
            int x = rand.nextInt(101)-50;
            int y = rand.nextInt(101)-50;
            Point p = new Point(x,y);
            this.points[i] = p;      // NullPointerException is thrown.
            this.numPoints = points.length;
        }
    }
}
Comments