1

I realize this is a common error, and I have tried to solve it using the other questions asked about this exact error, however I could not come up with a solution. I made an array of 10 cars, and am setting the make, color, and year of each of them. The getter and setter methods are in another class called "Car". I'm not sure where something is set to null. Thank you in advance for any help.

Error: Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:14)

import java.util.Random;

public class Main {

public static void main(String[] args) {

    //Array of 10 cars
    Car[] cars;
    cars = new Car[10];

    //Assign random colors and makes of my choice
    cars[0].setMake("Toyota");
    cars[1].setMake("Kia");
    cars[2].setMake("Porsche");
    cars[3].setMake("Ferrari");
    cars[4].setMake("Honda");
    cars[5].setMake("Jaguar");
    cars[6].setMake("Lexus");
    cars[7].setMake("Nissan");
    cars[8].setMake("BMW");
    cars[9].setMake("Tesla");

    cars[0].setColor("Black");
    cars[1].setColor("Green");
    cars[2].setColor("Silver");
    cars[3].setColor("Red");
    cars[4].setColor("Yellow");
    cars[5].setColor("White");
    cars[6].setColor("Blue");
    cars[7].setColor("Orange");
    cars[8].setColor("Purple");
    cars[9].setColor("Gold");

    //Randomly selected years for the cars
    int maxYear = 2015;
    int minYear = 2010;
    int maxYear2 = 2009;
    int minYear2 = 1990;

    Random r = new Random(1234);
    cars[0].setYear(r.nextInt(maxYear - minYear + 1) + minYear);
    cars[1].setYear(r.nextInt(maxYear - minYear + 1) + minYear);
    cars[2].setYear(r.nextInt(maxYear - minYear + 1) + minYear);
    cars[3].setYear(r.nextInt(maxYear - minYear + 1) + minYear);
    cars[4].setYear(r.nextInt(maxYear - minYear + 1) + minYear);
    cars[5].setYear(r.nextInt(maxYear2 - minYear2 + 1) + minYear2);
    cars[6].setYear(r.nextInt(maxYear2 - minYear2 + 1) + minYear2);
    cars[7].setYear(r.nextInt(maxYear2 - minYear2 + 1) + minYear2);
    cars[8].setYear(r.nextInt(maxYear2 - minYear2 + 1) + minYear2);
    cars[9].setYear(r.nextInt(maxYear2 - minYear2 + 1) + minYear2);

}

}
D.Khan
  • 143
  • 1
  • 6

1 Answers1

7

Initializing an array of objects does not initialize the objects contained in the array and hence you are getting NullPointerException.

Before you try to do this:

cars[0].setMake("Toyota");

you should first initialize your Car object like this:

cars[0] = new Car(); // or use any other appropriate constructor

same applies to rest of your objects in the array.

Juned Ahsan
  • 63,914
  • 9
  • 87
  • 123