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!");
}
看起来这将在数组中找到正确的记录。问题是它进入无限循环打印出结果。显示结果的最佳方法是什么?
答案 0 :(得分:4)
找到匹配项时需要中断:
if(Value.equals(ArrayList[Pivot].LastNamePlayer))
{
System.out.println(ArrayList[Pivot].NamePerson);
break;
}
答案 1 :(得分:0)
添加回报;到你发现的结尾和你的其他声明的结尾。它将终止while循环并结束函数。
if (Value.equals(ArrayList[Begin].LastNamePlayer)){
System.out.println(ArrayList[Begin].NamePerson );
return;
}
else if(Value.equals(ArrayList[End].LastNamePlayer))
System.out.println(ArrayList[End].NamePerson);
return;
else
System.out.println("Not Found!");
return;
}