0

I'm trying to build an array of objects, but getting a nullpointer exception when trying to set them.

Why when it gets to the first cars[i], it throws the exception?

Here is the code: Example 1: http://pastebin.com/4h4W3770 Example 2: http://pastebin.com/4GL4FhrW

3 Answers 3

2

When you create an array object, all its element are initialized to null (if array contains subclass of java.lang.Object). You need to instantiate each element before accessing any property . You are trying to set Cars property without instantiating it in the code below which is causing NullPointerException:

car[i].setPlate(info[0]);

Before doing this you need to initialize an instance of Car like this:

    public static void main(String[] args) {
        String sCurrentLine;
        try (BufferedReader br = new BufferedReader(new FileReader("cars.txt"))) {
            while ((sCurrentLine = br.readLine()) != null) {
                String[] info = sCurrentLine.split(",");
                for (int i = 0; i < 10; i++) {
                    car[i] = new Cars();   //instantiate Cars object or next statement will throw NPE
                    car[i].setPlate(info[0]);
                    car[i].setLocation(Integer.parseInt(info[1]));
                    car[i].setSpeed(Integer.parseInt(info[2]));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
Sign up to request clarification or add additional context in comments.

Comments

0

Your setter methods dont get any input / parameters, so they dont know what they should set:

public void setSpeed() {
    this.speed = speed;
}

Change to:

public void setSpeed(Integer speed) {
    this.speed = speed;
  }

2 Comments

Sorry, I used an old link in the question, I updated it and already fixed this. Any idea still?
Ah, your examples make more sense now. Think sud29 has the correct answer now.
0

You have a simple problem. you have never initialised car[i]. car[i] is null and when you try any operation to a variable that is null you get a NullPointerException.

So the solution is to initialise car[i] As shown below:

for (int i = 0; i < 10; i++) {
   car[i] = new Cars(); //intialise the car.
   car[i].setPlate(info[0]);
   car[i].setLocation(Integer.parseInt(info[1]));
   car[i].setSpeed(Integer.parseInt(info[2]));
}

This I think will solve your problem.

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.