Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, using an array of points

I am writing a program in Java, in which I define a class

class Point
{
    double x;
    double y;
}

Then in a method, I define an array of points, as follows:

Point[]     line = new Point[6];

In the same method, I have the line

line[SampleSize - i + 1].x = i;

The first time this statement is hit, the value of its array index is 1; but the program throws a null pointer exception at this point.

This would seem like the correct way to index the field of an object within an array of objects. What am I doing wrong?

Thanks in advance for any suggestions.

John Doner

like image 879
John R Doner Avatar asked Oct 12 '10 14:10

John R Doner


2 Answers

You have to initialize the value before accessing it:

line[SampleSize - i + 1] = new Point();
like image 83
Boris Pavlović Avatar answered Sep 30 '22 19:09

Boris Pavlović


That's because you have not created the points to put in the array

for (int index = 0; index < line.length; index++)
{
    line[index] = new Point();
}
like image 33
willcodejavaforfood Avatar answered Sep 30 '22 20:09

willcodejavaforfood