gpt4 book ai didi

java - Java toString 中的 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 02:56:57 25 4
gpt4 key购买 nike

我正在尝试实现一个简单的测验游戏,并且在我的 Question 中重写 toString 方法时类我得到一个 NullReferenceException。问题从何而来?这是我在问题类中的代码

    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());
}
}

最佳答案

你的构造函数没有任何意义。

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

您正在传递一个数组,但您没有使用它。您只需创建一个新数组。我认为你想将它用作成员变量。因此,您必须删除构造函数中的第二行:

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

您的数组答案始终只有空值,因此您会收到错误。

根据注释进行编辑,数组的大小应为 4:

    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;
}
}

关于java - Java toString 中的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42935622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com