二分查找 - 显示结果
public void Find() {
String Value = "";
System.out.println("Search Name");
Value = Input.next();
int Begin, End, Pivot;
Begin = 0;
End = CurrentCount;
while(End - Begin > 1 ) {
Pivot = Begin + (End - Begin)/2;
if(Value.equals(ArrayList[Pivot].LastNamePlayer))
System.out.println(ArrayList[Pivot].NamePerson);
else if(Value.compareTo(ArrayList[Pivot].LastNamePlayer) < 0)
End = Pivot;
else
Begin = Pivot;
}
if (Value.equals(ArrayList[Begin].LastNamePlayer))
System.out.println(ArrayList[Begin].NamePerson );
else if(Value.equals(ArrayList[End].LastNamePlayer))
System.out.println(ArrayList[End].NamePerson);
else
System.out.println("Not Found!");
}
看起来这将在数组中找到正确的记录。问题是它进入无限循环打印结果。显示结果的最佳方式是什么?
public void Find() {
String Value = "";
System.out.println("Search Name");
Value = Input.next();
int Begin, End, Pivot;
Begin = 0;
End = CurrentCount;
while(End - Begin > 1 ) {
Pivot = Begin + (End - Begin)/2;
if(Value.equals(ArrayList[Pivot].LastNamePlayer))
System.out.println(ArrayList[Pivot].NamePerson);
else if(Value.compareTo(ArrayList[Pivot].LastNamePlayer) < 0)
End = Pivot;
else
Begin = Pivot;
}
if (Value.equals(ArrayList[Begin].LastNamePlayer))
System.out.println(ArrayList[Begin].NamePerson );
else if(Value.equals(ArrayList[End].LastNamePlayer))
System.out.println(ArrayList[End].NamePerson);
else
System.out.println("Not Found!");
}
It looks like this will locate the proper record in the array. The problem is that it goes into an infinite loop printing out the result. What is the best way to display the result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当你找到匹配项时,你需要中断:
You need to break when you find the match:
添加返回;到 if found 的末尾和 else 语句的末尾。它将终止 while 循环并结束函数。
Add a return; to the end of your if found and to the end of your else statement. It will terminate the while loop and end the function.