Trying to create an object and adding it to an ArrayList. Code looks similar to this:
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)
And in the debugger, right before the crash I get this:
Thread.dispatchUncaughtException(Throwable) line: not available
It’s crashing at
answerList.add(new StringAnswer());
and I have no idea why.
If it’s relevant, questionList is initialized in the superclass of where this code chunk is. I am accessing it because it is protected. answerList is created locally.
The constructor of StringAnswer asks the user for a String and reads it via Scanner. EssayQuestion()’s constructor is very similar.
Any ideas?
Edit: Here is some more code as requested. Yes, answerList is showing as null after initialized and before anything gets added. Is that the problem? Why is it happening? Once again, questionList is declared and initialized in the parent class of this, so it’s okay not to re-declare or initialize it right?
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;
And here is 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;
}
}
From your comments to @D_Jones’s answer, I assume you’ve something like this:
And after that you’re accessing questionList and trying to add elements to it from your Test class. The problem over here is this that you’ve not instantiated questionList. This means that questionList is still null and when you’re trying to add elements to questionList, you’re thrown a NullPointerException by the JVM.
There’re a couple of solutions to it:
Solution 1: Instantiate questionList in the base class constructor. Something like this:
Now you can access it in your child class without an exception.
Solution 2: Instantiate it within the constructor of your child class or wherever you’re trying to use it for the first time.