-4

I was working on this code to take in a target String and search the linked list for the target and delete all instances of it. I feel like I have most of the logic down but I am getting a NullPointerException and was needing some help. here is the code:

public class LinkedStringLog implements StringLog {
  private LLStringNode head;
  private int numOfEntries;


  public LinkedStringLog() {//constructor
    head = null;
    numOfEntries = 0;
    }


  public void delete(String target){//deletes all entries of target

    LLStringNode current = head;
    LLStringNode prev = head;

    for (int i = 0; i < numOfEntries; i++) {
        prev = current;
        current = current.getNext();

        if (target.equals(current.getValue())){
            prev.setNext(current.getNext());
            current.setNext(null);
            numOfEntries--;

        }
    }

}

  • Well, you've left out your `LLStringNode` code, as well as any code that adds to this list. Also you don't nullcheck `current` or `prev` at any point. And you neglected to mention which line the error is on. Overall, this question is lacking a ton of information. – CollinD Feb 23 '16 at 04:59

1 Answers1

-1

you have to initialize current and prev with a not null reference!...

current = head;
prev = head; 

but head is set to null in the constructor...

current.getNext();

since current is not initialized, that is a nullpointer exception

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • `current = head`. It is initialized. And if his code that adds nodes works, then the loop would not be entered as `numOfEntries` would be zero. Needs more code to be determined. – CollinD Feb 23 '16 at 05:01
  • yes, but init with null... thanks anyway – ΦXocę 웃 Пepeúpa ツ Feb 23 '16 at 05:03
  • As I said, xoce, presumably there is additional code that adds elements, updates head, and increments numOfElements. You cannot possibly determine the issue without more code. Assuming the present code is complete, it won't even generate an error since `numOfEntries` is zero. – CollinD Feb 23 '16 at 05:04