2011-05-22 92 views
2
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!"); 
    } 

看起來像這樣會在數組中找到正確的記錄。問題在於它會打印出結果的無限循環。顯示結果的最佳方式是什麼?二進制搜索 - 顯示結果

回答

4

你需要打破當你發現比賽:

if(Value.equals(ArrayList[Pivot].LastNamePlayer)) 
{ 
    System.out.println(ArrayList[Pivot].NamePerson); 
    break; 
} 
+0

如果我添加一個break;否則,如果跟着它不起作用。 – chief 2011-05-22 01:26:28

+2

你用過括號嗎? – MByD 2011-05-22 01:27:06

0

添加回報;到你找到的盡頭和你的else語句的結尾。它將終止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; 
}