Java using an array of points

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

class Point { double x; double y; } 

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

 Point[] line = new Point[6]; 

In the same method, I have a line

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

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

It would seem that this is 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

+4
source share
7 answers

Just to add an answer to Boris, here is some code

 class Point { double x; double y; } Point[] line = new Point[6]; for(int i = 0; i < line.length; i++) { line[i] = new Point(); } // now you can set the values, since the point aren't null line[0].x = 10; line[0].y = 10; 
+3
source

You must initialize the value before accessing it:

 line[SampleSize - i + 1] = new Point(); 
+4
source

This is because you did not create points for placement in the array

 for (int index = 0; index < line.length; index++) { line[index] = new Point(); } 
+4
source
 Point[] line = new Point[6]; 

creates an empty array capable of holding points. But so far it does not refer to the point. All values ​​are zero.

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

trying to access x on null .

+4
source

http://java.sun.com/docs/books/jls/third_edition/html/arrays.html

If you check in Section 10.2, the action of creating an array simply creates links, but not objects. Therefore, the cause of your null pointer error for all references is assigned the default value, which in this case is null.

+2
source

Although you have allocated an array, the contents of the array are null. What you need to do:

 Point[] line = new Point[6]; for (int i = 0; i < line.length; i++) { line[i] = new Point(); } 
+2
source

When you first create an array, it contains six null references.

Before you can interact with objects in an array, you need to create objects, for example:

 line[someIndex] = new Point(); 

You probably want to initialize each point in the array with a for loop.

+1
source

All Articles