I am trying to implement a simple Quiz Game and when overriding toString method in my Question
class I got a NullReferenceException. Where the problem comes from? This is my code in Question class
public class Question {
private String text;
private Answer[] answers;
private final static int ANSWER_SIZE_ARRAY = 4;
public Question(String text, Answer[] answers) {
this.text = text;
answers = new Answer[ANSWER_SIZE_ARRAY];
this.answers = answers;
}
public void setText(String text) {
this.text = text;
}
public void setAnswers(Answer[] answers) {
this.answers = answers;
}
public String getText() {
return this.text;
}
public Answer[] getAnswers() {
return this.answers;
}
//test toString
public String toString() {
String result = this.getText() + "\n";
for (Answer a : this.answers) {
result += a.getText() + "\n"; // HERE COMES THE PROBLEM
}
return result;
}
}
And my main method is like:
public class MainGameTestMethod {
public static void main(String[] args) {
Answer a1 = new Answer("Krisko", true);
Answer a2 = new Answer("Beatz", false);
Answer a3 = new Answer("Ivan", false);
Answer a4 = new Answer("Pesho", false);
Question q1 = new Question("Whats your name?", new Answer[] { a1, a2, a3, a4 });
System.out.println(q1.toString());
}
}