1
public class LString{
   char data;      //chars stored in this node
   LString next;   //link to next LString node 

  public LString(char newdata){
     data = newdata;
  }

  public LString(char newdata, LString newnext){
     data = newdata;
     next = newnext;
  }

  public LString(){
  }

  //create a front of list
  LString front;

  //create length of list
  int length;

  /*Construct an LString object. The LString object will represent the
  same list of chars as original. That is, the newly created LString is a
  "copy" of the parameter original.*/

  public LString(String original){
     LString curr = front;
     for(int i = 0; i < original.length(); i++){
        curr.data = original.charAt(i);
        curr = curr.next;
        length++;
     }
  }
}

public class test{
     public static void main(String[] args){
        LString myList = new LString("hi");
     }
}

The following code should put the string "hi", into a linked list of chars, where each letter of hi, is one node of the list. When ran, it gives a nullpointerexception pointing to the line curr.data = original.charAt(i);. Why is there a null pointer exception there? Thank you

user39423
  • 11
  • 1
  • do you have an example of your main driver program, showing how you are using this class? – pczeus Feb 25 '16 at 01:08
  • 1
    I don't see `front` being initialized anywhere? and yet you assign it to `LString curr` so therefore that will be null. So change `LString front` to `LString front = new LString();` – 3kings Feb 25 '16 at 01:10

1 Answers1

1

In your loop:

public LString(String original){
 LString curr = front;
 for(int i = 0; i < original.length(); i++){
    curr.data = original.charAt(i);
    curr = curr.next;
    length++;
 }

}

The first iteration through, you set curr.data to the first character in the original String. You then set curr to the value at curr.next - which is null.

Therefore, the second iteration, when you try to access curr.data, curr is null so the exception is thrown.

You need to take into account that on the first character of the string, you haven't yet set the front, so setting next is premature. Change your code to check for the first element and don't set next in this case:

public LString(String original){
  LString curr = null;

  for(int i = 0; i < original.length(); i++){
    char ch = original.charAt(i);

    if(i == 0){
        front = new LString(ch);
        curr = front;
    }
    else{
        curr.next = new LString(ch);
        curr = curr.next;
    }
    length++;
  }
}
pczeus
  • 7,709
  • 4
  • 36
  • 51