シンプルなクイズゲームを実装しようとしていて、Question
クラスのtoStringメソッドをオーバーライドするときにNullReferenceExceptionが発生しました。問題の原因はどこですか?これは、質問クラスで私のコードJava toStringのNullPointerException
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;
}
}
され、私の主な方法は次のようである:
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());
}
}
は[ANSWER_SIZE_ARRAY] = '新しい回答の回答を削除し、' CTORから。 –
コンストラクタでは、 'this.answers'をサイズ4の空の配列に設定します。これは4つの' null'オブジェクトの配列です。その後、その配列をループし、それらの 'null'オブジェクトを使用しようとします。 – David
コンストラクタのパラメータ'answers = new ... 'を上書きしていますが、その行は必要ありません。 – MikaelF