1

I created a class Car. It includes a location, a double array size 2. I'm trying to create an array of Cars. Here is what I have:

Car[] cars;
cars = new Car[3];

cars[0].location = new double[]{1,6};
cars[1].location = new double[]{10,30};
cars[2].location = new double[]{20,7};

I get an error where I try to declare the location: NullPointerException. How do I resolve this?

1
  • 3
    You haven't initialized the elements in the array. Commented Feb 2, 2014 at 2:07

1 Answer 1

4

You need to create reference variables for the objects in the array. Your original code simply initializes a Cars array of size 3, but doesn't put any objects inside.

Car[] cars;
cars = new Cars[3];

for (int i=0; i<3; i+=1) {
    cars[i] = new Car();
}

cars[0].location = new double[]{1,6};
cars[1].location = new double[]{10,30};    
cars[2].location = new double[]{20,7};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.