Reputation: 35
I want to search in linked list with scanner but i cannot do it. I can search without scanner. What is wrong with this code?
My search method:
public void Search(Object data){
Node tmp = head ;
while(tmp != null ){
if(tmp.getData() == data){
System.out.println("Your input is in the list");
}
tmp = tmp.getNext();
}
}
And my main class:
public static void main(String[] args) throws ParseException {
LinkedList list =new Linkedlist();
...... // adding methods etc.
Scanner input = new Scanner(System.in);
System.out.println("Enter your input: ");
String x=input.next();
list.Search(x);
}
Upvotes: 0
Views: 1707
Reputation: 431
To build on what Adam has suggested, you can consider the following code:
public void Search(String data){
Node tmp = head ;
while(tmp != null ){
if(tmp.getData().equalsIgnoreCase(data)){
System.out.println("Your input is in the list");
}
tmp = tmp.getNext();
}
}
You should use .equals() or .equalsIgnoreCase() to compare the string instead of comparing by == which compares each other as objects.
What is the difference between == vs equals() in Java?
Upvotes: 1
Reputation: 76
You are passing the String
parameter into search(data)
, which is being cast as an Object
.
You will need to either type-cast the Object data
parameter to type String
, or change the method signature to explicitly accept type String
Upvotes: 1