-2

If I use l.search("Hi"); the code will run fine but if I pass String s to search method, it will prompt an error NullPointerException

System.out.print("Search: ");
         String s = scan.next();
         l.search(s); 

public void search(String name){
      Node current = tail;
         while(current != null && current.name != name){
            current = current.previous;
         }
         
         if(current.name == name){
            System.out.println("Item found.");
         }   
   }
Grwolfy
  • 19
  • 3
  • 1
    `current.name != name` -> [How do I compare strings in Java?](https://stackoverflow.com/q/513832) – Pshemo Dec 21 '20 at 16:32

1 Answers1

-1

You have several issues here. A null pointer exception occurs when you try to reference an object that doesn't exist. If "s" hasn't been initialized, referring to it causes a null pointer exception.

To compare strings use methods like myFirstString.equals(stringComparingTo) which returns an integer. If I recall this equals zero when the two strings are equal (or current.name.equals(name)==0 - in your case). This assumes "name" is a field of your "node" class.

Dr Dave
  • 550
  • 1
  • 6
  • 22