i have a 2 data classes
first:
public class Question {
public CharSequence question;
public Answer answers[];
}
second:
public class Answer {
public CharSequence text;
public int number;
}
now i want to save an Answer to Question:
Question qstn.answers = new Answer[2];
[...]
But i got an NullPointerException. Whats wrong? Can’t I change the length of an Array in an other class?
Have you created a new instance of Question first e.g.
Also unless you’re optimising judiciously, then you’d probably want to give encapsulation a go and make the instance variables private. Access through a public API e.g. getters or/and setters.
Also you may want to instantiate answers when the Object is created e.g.
Or you could do this in the constructor of Question (you’d need to add a Constructor, as the compiler will be generating you a non-arg Constructor by default with the way things stand).