I’m new to list and I have a problem with the method below:
the problem is: java.lang.NullPointerException
Code:
public static List<Integer> input(List<Integer> l)
{
Node<Integer> pos=l.getFirst();
System.out.println("Enter num (!=999)");
int x = reader.nextInt();
l.insert(null, x);
while(x!=999)
{
System.out.println("Enter num (!=999)");
l.insert(pos, x);
pos = pos.getNext();
}
return l;
}
Silly me I forgot the input message inside the while…
If you initialized
las an empty list, then the call towould return
null. Then later, you callpos.getNext();on anullinstance, hence theNullPointerException. One way to fix this would be to handle the possibility of the empty list inside yourwhileloop, like this:When you run this, you’ll see the second problem in your code, which you should be able to resolve.
Good luck!