尝试创建一个对象并将其添加到 ArrayList。代码与此类似:
class B{
public ArrayList<Answer> answerList = new ArrayList<Answer>();
questionList.add(new EssayQuestion());
answerList.add(new StringAnswer());
}
Exception in thread "main" java.lang.NullPointerException
at main.Test.createNewQuestion(Test.java:31)
at main.Survey.<init>(Survey.java:21)
at main.Test.<init>(Test.java:9)
at main.MainDriver.main(MainDriver.java:35)
在调试器中,就在崩溃之前,我得到了这个:
Thread.dispatchUncaughtException(Throwable) line: not available
它崩溃了
answerList.add(new StringAnswer());
,我不知道为什么。
如果相关,questionList 会在该代码块所在的超类中初始化。我正在访问它,因为它受到保护。answerList 在本地创建。
StringAnswer 的构造函数向用户询问一个 String 并通过 Scanner 读取它。EssayQuestion() 的构造函数非常相似。
有任何想法吗?
编辑:这是根据要求提供的更多代码。是的, answerList 在初始化后和添加任何内容之前显示为 null。那是问题吗?为什么会这样?再一次,在this的父类中声明并初始化了questionList,所以不重新声明或初始化也没关系吧?
public class Test extends Survey
{
public ArrayList<Answer> answerList;
public Test()
{
answerList = new ArrayList<Answer>();
System.out.print("How many questions? ");
int numQuestions = kb.nextInt();
for (int i = 0; i < numQuestions; i++)
{
displayMenu();
createNewQuestion();
}
}
public void createNewQuestion()
{
int input = -1;
do{
System.out.print("Question Type: ");
input = kb.nextInt();
System.out.println();
switch (input)
{
case 1: questionList.add(new EssayQuestion());
answerList.add(new StringAnswer());
break;
这是StringAnswer:
public class StringAnswer extends Answer
{
String text;
public StringAnswer()
{
setAnswer();
}
public StringAnswer(String text)
{
this.text = text;
}
@Override
public void display()
{
System.out.println(text);
}
public String getAnswer()
{
return text;
}
@Override
public void setAnswer()
{
System.out.print("Enter Answer: ");
setAnswer(kb.nextLine());
System.out.println("");
}
public void setAnswer(String text)
{
this.text = text;
}
}