Reputation: 5
im working a search method on a linked list this my code
Node item=head;
String help=item.getKonten();
System.out.printf("data to search");
search=input.nextLine();
while (help.compareTo(search)>0){
if (help.equals(search)){
System.out.println ("index " + index);
ktemu=1;
} else {
item=item.getLink();
bantu1=item.getKonten();
}
index++;
}
if (ktemu == 0){
System.out.println("data not found");
}
the output data : 1,2,3,4,5 data to search 2 data not found anyone can point me whre this code goes wrong so the index not shown up
Upvotes: 0
Views: 320
Reputation: 15675
You are iterating for as long as bantu1
is not the same as cari
, but you do so using the compare interface. Why not use equals directly? Anyway, if you do want to use the compare method, as @Quoi says, you need to consider that it might be < 0, so, !=0
might be more suitable.
How about this:
private boolean find(Object input);
while (true){
if(item.equals(input)){
return true;
} else {
if(item.getLink() == null) {
return false;
} else {
item=item.getLink();
}
}
}
}
Upvotes: 0
Reputation: 41200
compareTo
method returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
So when you compare 1 with 2 which return negative value and -1>0
becomes false. So it come out of loop.
Upvotes: 2