-7

I've created a custom class called Person. Now I want to use the person class the same way you can with a String or int class, by turning them into a table when I create a variable with the person class.

Person[] persons = new Person[3];

But when I do it like this, I get the error: NullPointerException. Is there any way to fix it, so I can use the person class as a list?

This is my person class:

class Person{
  //Definerer navn og posisjonen.
  String navn;
  String[] interesser = new String[4];

  //Funksjonen for aa sette navn.
  void settNavn(String navn){
    this.navn = navn;
  }

  //Funksjonen for aa sette interesser.
  void settInteresser(String interesser, int index){
    this.interesser[index] = interesser;
  }

  //Funksjonen for aa hente navnet.
  String hentNavn(){
    return navn;
  }

  //Funksjonen for aa hente interessene.
  String hentInteresser(int index){
    return interesser[index];
  }
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Chris
  • 3
  • 2
  • 11
    Umm, this definitely isn't JavaScript. – James Wright Sep 29 '15 at 15:21
  • @Chris Java are we ? – ShrekOverflow Sep 29 '15 at 15:23
  • 1
    The Java motion passes. Next case. – Sterling Archer Sep 29 '15 at 15:24
  • @Chris: What language is this? You say `NullPointerException`, so is this Java? Note: Java is to JavaScript as car is to carpet. – gen_Eric Sep 29 '15 at 15:24
  • 2
    Welcome to Stack Overflow! Please take the [tour], have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) You've said you're getting an error, but you haevn't shown the code giving you that error; instead, you've shown code using `String`. `Person[] persons = new Person[5];` works just fine. We can't help you with code we cannot see. Also note that Java and JavaScript are **completely** different languages and environments. – T.J. Crowder Sep 29 '15 at 15:27
  • 1
    possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Mark Rotteveel Sep 29 '15 at 18:18

1 Answers1

1

You are not creating any Person objects. You are creating a Person array with space to hold some Person objects, but I will bet you pounds to pence that you aren't populating that array with a single Person. It is an empty array.

You might write:

Person[] persons = new Person[3];
persons[0]=new Person();

Now you can call methods of persons[0] without getting a NullPointerException. Populate the other 2 elements in the array in the same way.

Breandán Dalton
  • 1,619
  • 15
  • 24
  • Thanks a lot, this was exactly what I was looking for. Using custom classes in this way is still a bit new to me. – Chris Sep 29 '15 at 20:24