2

I am attempting to add a node to the end of my linked list, i get a null pointer exception when i get to the else statement and try to set problem.rear.next to the new node I am adding. For some reason when i attempt to set the rear.next pointer to a new node the exception pops up.

To clarify,

The BigIntegerList is a linked list of nodes which are also linked lists that represent a Big integer by linking individual integers together. The big integer list defines a "start" and "rear" node, The BigInteger node defines "x" for the data and "next" for a pointer to the next node in the list.

Also,

problem.n represents the number of BigIntegers to be read in, the method reads from a text file, the first number read states how many big integers are going to be read followed by the actual BigIntegers

Any ideas welcome as I am very stuck....

BigIntegerList problem;
   LinkedList x;
   BigIntegerNode curr;

   problem = new BigIntegerList();
   //get value of first line stating #of bigInts to read in
   problem.n = LinkedList.readInteger(in);
   //read big ints from text file based on first number passed, n
   for(int i=0; i<problem.n;i++)
   {
     x = new LinkedList();
     x.readBigInteger(in);
     //case that the list is empty
     if(problem.n<1)
     {
       problem.start = new BigIntegerNode(x,null);
       problem.rear = problem.start;
     //list is not empty, add nodes to rear
     }else
     {
       curr = new BigIntegerNode(x,null);
       problem.rear.next = curr; -----> this is where i get a nullpointer....
       problem.rear = curr;
     }
   }
   return problem;
justDare
  • 55
  • 5
  • 2
    Looking at your code, it would seem that `if (problem.n < 1)` will always evaluate to `false`. Hence your `else` block always executes with `problem.rear` still `null`. Have you tried stepping through with your debugger? – dave Oct 11 '17 at 04:54

1 Answers1

0

As @dave suggests, change if (problem.n < 1) to

If (i < 1) {

problem.n is the total number of iterations the loop will do, ie a constant. i is the loop's counter. It will be set to 0 in the first iteration, and then to 1, 2, 3, ..., (problem.n)-1

Since you want to the if statement to evaluate to true in the first iteration, let it look at i instead of problem.n

Stefan
  • 2,395
  • 4
  • 15
  • 32
  • Would you mind explaining it a little more? For the sake of new users who might read this answer. – Shirkam Oct 11 '17 at 06:28