0

So I'm currently working on something and I came to the following problem:

I have a class "person" with the paramters name, age, gender. I also have a class "group" with the parameters groupname, room and a two dimensional array from type person. So it all looks like this:

public class person{
 private String name;
 private int age;
 private String gender;

 public person(){}
 public setName(String name){this.name=name;}
 public setAge(int age){this.age=age;}
 public setGender(String gender){this.gender=gender;}
}


public class group{
 private String groupname;
 private String room;
 private person[][] persons;

 public group(int X, int Y){persons = new person[X][Y];}
}

To create a group you have to give the size of the array. In order to fill the persons Array now there is the following function:

public setPerson(int X, int Y, String name, int age, String gender){
 persons[X][Y].setName(name);
 persons[X][Y].setAge(age);
 persons[X][Y].setGender(gender);
}

Now I use this logic:

group NewGroup = new group(2,0);
NewGroup.setPerson(0,0,"John",7,"male");
NewGroup.setPerson(1,0,"Paul",9,"male");
NewGroup.setPerson(2,0,"Jen",8,"female");

But when I do this it gives me the following exception:

Exception in thread "main" java.lang.NullPointerException

So it seems to me as if the Array hasn't been created properly. Where's my mistake?

(I know this is all weird, but I need the two dimensional array for later stuff)

Ruben
  • 3
  • 1
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Carcigenicate Feb 22 '19 at 16:20
  • Welcome to StackOverflow. Your code as you've shown it actually 1) doesn't compile, because your methods don't have return types, and 2) throws not `NullPointerException`, but `ArrayIndexOutOfBoundsException`, since by calling `new group(2, 0)` you create a two-element array with two zero-element arrays inside. There's no 0th element in a zero-length array. – Forketyfork Feb 22 '19 at 16:32
  • (Tops, *`instance.set…()`* is an antipattern.) – greybeard Feb 22 '19 at 17:13

1 Answers1

3

The problem is you instantiate the array but not the individual objects. Before you do persons[X][Y].setName(name); you should do this:

persons[X][Y] = new person();

Also, you should consider renaming your variables and classes to follow convention.

Ayrton
  • 2,218
  • 1
  • 14
  • 25