2017-03-21 9 views
0

シンプルなクイズゲームを実装しようとしていて、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()); 
    } 
} 
+0

は[ANSWER_SIZE_ARRAY] = '新しい回答の回答を削除し、' CTORから。 –

+0

コンストラクタでは、 'this.answers'をサイズ4の空の配列に設定します。これは4つの' null'オブジェクトの配列です。その後、その配列をループし、それらの 'null'オブジェクトを使用しようとします。 – David

+0

コンストラクタのパラメータ'answers = new ... 'を上書きしていますが、その行は必要ありません。 – MikaelF

答えて

2

あなたのコンストラクタはどんな意味がありません。

public Question(String text, Answer[] answers) { 
     this.text = text; 
     answers = new Answer[ANSWER_SIZE_ARRAY]; 
     this.answers = answers; 
    } 

あなたは配列を渡していますが、使用しません。新しい配列を作成するだけです。私はあなたがメンバー変数としてそれを使用したいと思います。したがって、あなたは、コンストラクタの2行目を削除する必要があります。

public Question(String text, Answer[] answers) { 
     this.text = text; 
     this.answers = answers; 
    } 

ご使用のアレイの答えは常にNULL値のみを持っているため、エラーが発生します。なぜなら配列のサイズ4持っているべきであることをcommentarの

編集:

public Question(String text, Answer[] answers) { 
     this.text = text; 
     if(answers == null || answer.length != 4){ 
      //do some exception handling e.g. throw error 
     //or do 
      //if(answer != null){ 
// take care that this method could also lead to null values in your new array if the old arrays length is < 4 
     // this.answers = Arrays.copyOf(answers, 4); 
     // } 

     } 
     else{ 
      this.answers = answers; 
     } 
    } 
+0

私は回答の数を4 – user7460099

+0

に修正したいと思いましたが、私は答えを更新しました。しかし、入力がサイズ4でない場合、あなたが何をしたいのか分からないので、私はちょうどインスピレーションを与えることができます;) – Markus

+1

注:['Arrays#copyOf'](https://docs.oracle) .com/javase/8/docs/api/java/util/Arrays.html#copyOf-T:A-int-)元の配列のコピーを作成する(指定した範囲で) - コードを少し短くする – UnholySheep

関連する問題