1

I'm getting a NullPointerException for the code below, and I don't quite understand why (or how to fix it). I know that my first node (next) is null, and that I can't call any methods on it without causing a null pointer exception, but I can't make it 'not null' without calling any methods on it :(. The null pointer exception is thrown in the first for loop in the insert function.

Here's my node class:

public class Node {

public Node next;
public String word;

public Node(String word){
    this.word = word;
}

public void display(){
    System.out.println (word);
}

public String toString(){
    return word;
}

And here's my linked list class

public class WordLinkedList {

private int size; //integer to store the size of the linked list (# of words)
private Node firstnode; // reference to first node

public WordLinkedList(){
    size = 0;
    firstnode = new Node(null); // setting first node to null - dummy node ... I think ???!!!
}

   public WordLinkedList(String[] arrayOfWords){
    for (int i = 0; i < arrayOfWords.length; i++){
        this.insert(arrayOfWords[i]);
    }
} 

public void insert(String newword){

   Node newNode = new Node(newword);

   for (Node iterator = firstnode.next; iterator != null; iterator =        newNode.next){
        if (iterator.word.compareTo(newword) < 0){
            if (iterator.next.word.compareTo(newword)>0){
                newNode.next = iterator.next;
                iterator.next = newNode;
            }
        }
        if (iterator.word.compareTo(newword) > 0){
            iterator.next = iterator;
            firstnode.next = newNode;
        }
    }
}

public void display(){
    Node theNode = firstnode;

    while (theNode != null){
        theNode.display();
        System.out.println("Next node: " + theNode.next);
        theNode = theNode.next;
        System.out.println();
    }
}

}

kenju
  • 5,866
  • 1
  • 41
  • 41
Bg601
  • 49
  • 1
  • 7
  • If you can convince me that your question isn't a dupe, then I'll reopen it. Since you have a good idea as to why you're getting the NPE, you should look into why you're taking that approach to begin with. Write out the steps on a piece of paper, then see if your code reflects that. – Makoto Jan 31 '15 at 18:51
  • If it's the first node being inserted, just set it as the firstNode. That node won't have any `next` node so far. – Hugo Sousa Jan 31 '15 at 18:52
  • Well, the reason I'm using the for loop is to insert nodes with actual data into the linked list. I can't start the loop at firstnode because that's supposed to be null; so I start it at firstnode.next - - > which should be the node firstnode references (first node in list with actual data). My problem is I don't know how to make firstnode.next not have a null value, if it begins with a null value. – Bg601 Jan 31 '15 at 19:00
  • Just compare the `firstNode` with `null`. If it's `null`, then your list is empty yet. – Hugo Sousa Jan 31 '15 at 19:16

0 Answers0