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?

J86
  • 14,345
  • 47
  • 130
  • 228
  • 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? – Hovercraft Full Of Eels Nov 09 '13 at 19:06
  • 1
    could you post the stack trace? – Math Nov 09 '13 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. :) – J86 Nov 09 '13 at 19:13

1 Answers1

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373