1

I'm basically trying to create a program that accepts user-input to insert into a singly linked list, then searches if said a certain element exists in the linked list. The problem is that all I'm getting for an output is "does not exists", even if it has been inserted at the beginning of the program.

For some reason, using initialized values, eg. "llist.push("test")" works, but using "llist.push(item)", which uses user-input, doesn't work. I've tried looking for similar problems online, but can't find any, please help me as I'm new to Java. Thanks in advance!

class Node 
{ 
    String data; 
    Node next; 
    Node(String d) 
    { 
        data = d; 
        next = null; 
    } 
} 

public class javalinkedlist
{ 
    Node head = null;
      public void push(String new_data) 
    {  
    Node new_node = new Node(new_data); 
    new_node.next = head; 
    head = new_node; 
} 

public boolean search(Node head, String x) 
{ 
    Node current = head; 
    while (current != null) 
    { 
        if (current.data == x) 
            return true; 
        current = current.next; 
    } 
    return false;
} 

public static void main(String args[]) 
{ 
    LinkedList llist = new LinkedList(); 
    Scanner input = new Scanner(System.in);
    System.out.print("Enter: ");
    String item = input.next();
    llist.push(item); 
    if (llist.search(llist.head, "test")) 
        System.out.println("exists"); 
    else
        System.out.println("does not exist"); 
} 

}

CodeWalker
  • 2,281
  • 4
  • 23
  • 50
Cha0stra
  • 11
  • 2
  • You are comparing strings using `==`. Use `equals` instead, as `==` compares identity, not _content_. – Zabuzard Oct 13 '19 at 07:36

0 Answers0