我在链接列表上运行搜索方法这是我的代码
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");
}
输出 数据:1,2,3,4,5 要搜索的数据2 数据未找到 任何人都可以指出我这个代码出错了所以索引没有显示
答案 0 :(得分:2)
compareTo
方法返回负整数,零或正整数,因为此对象小于,等于或大于指定对象。
因此,当您将1与2进行比较时返回负值并且-1>0
变为false。所以它就会失控。
答案 1 :(得分:0)
只要bantu1
与cari
不同,您就会进行迭代,但是您可以使用比较界面进行迭代。为什么不直接使用equals?无论如何,如果你想使用比较方法,正如@Quoi所说,你需要考虑它可能< 0,所以,!=0
可能更合适。
这个怎么样:
private boolean find(Object input);
while (true){
if(item.equals(input)){
return true;
} else {
if(item.getLink() == null) {
return false;
} else {
item=item.getLink();
}
}
}
}