Nullpointerexception error with class composition

Asked

Viewed 54 times

0

I have a class called Users, which has as attribute an array of type Sensors

protected Sensors sensors[10];

It also has the setDescription method

public void setDescription (int ind, String description)
{
    this.sensors[ind].description = description;
}

After instantiating an object called user, I tried calling by the method like this:

user.setDescription (ctr, description);

but is giving Nullpointerexception. If anyone can help me, I am grateful.

  • Only with this can not help much. One thing you can do is to check whether the object sensors is null before accessing it, but will not do much, does not solve the problem in fact. You need to see the rest of the class because it is not initialized or some element of the array is not initialized. You probably need to initialize in the constructor but I can’t say with this information alone.

  • well, I’m calling the constructor like this: user.Sensors[Ctr] = new Sensors(name2, Description); but I don’t know if it’s correct

  • The problem is the code inside the constructor. As I said if you do not put all your code, it will be difficult to identify where your problem is. I will showed the symptom, the cause is hidden.

1 answer

2

This happened because the attribute protected Sensors sensors[10] was not initialized.

You can do this, either in the constructor or in the attribute statement itself, in this way: protected Sensors[] sensors = new Sensors[10];

  • If the answer has solved your problem, please mark it as correct by clicking the green arrow below the arrows of the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.