1

I am trying to add an object of type Car to an Array of cars, I do not have a specific index within the array that I want the car to go into, I just want to add the car to the first empty and available index that doesn't have a car object already in there. Here is my code:

protected static final int MaxCars = 5;
protected Car[] cars = new Car[MaxCars];
public void addCar(Car c)
{
 for(int i = 0; i < MaxCars; i++)
 {
 if (cars[i] == null)
 {
 cars[i] = c;
 break;
 }
 }
 incrementNumInTeam();
}

On the if statement inside the for loop I am getting the a NullPointerException .. how can I overcome this?

asked Nov 9, 2013 at 19:05
3
  • 5
    Your variable cars is likely null at the time the if block is called. Your error is present but likely elsewhere in your code. Are you sure that you're not shadowing the cars variable? That the variable being initialized is the same one being read? Commented Nov 9, 2013 at 19:06
  • 1
    could you post the stack trace? Commented Nov 9, 2013 at 19:07
  • 1
    Hovercraft can you write yours as an answer please. What you said made me realize that I had missed the initialization in the constructor that was being called. :) Commented Nov 9, 2013 at 19:13

1 Answer 1

3

Your variable cars is likely null at the time the if block is called. Your error is present but likely elsewhere in your code. Check to be sure that you're not shadowing the cars variable and that the variable being initialized is the same one being read.

answered Nov 9, 2013 at 19:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.