2011-03-02 106 views
0

我有一個String,double和float類型的數組,我需要能夠在其中搜索字符串。我試圖做一個二進制搜索,但我發現了以下錯誤,當我運行該程序,並嘗試搜索:在字符串中搜索多維數組

java.lang.ClassCastException: java.lang.String cannot be cast to Customer 
    at Customer.compareTo(prog4.java:1) 
    at java.util.Arrays.binarySearch0(Unknown Source) 
    at java.util.Arrays.binarySearch(Unknown Source) 
    at prog4.main(prog4.java:59) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    at java.lang.reflect.Method.invoke(Unknown Source) 
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271) 

我還沒有找到搜索以3D陣列的任何其他方法,所以任何幫助將不勝感激。

這裏是我的代碼:

case 'b': 
     System.out.println(); 
     System.out.println("Please enter a customer name:"); 

     String search = kb.nextLine(); //read the user's search 
     int place; //location of result 

     Arrays.sort(A); 

     place = Arrays.binarySearch(A, search); 

     if (place <= 0) 
     System.out.println("Cannot find customer named " + search); 
    else 
    { 
     System.out.println("Customer found:"); 
     System.out.println(A[place]); 
    } 

      break; 
+0

地方 - 你鑄塑'Customer'哪裏,你應該把它轉換爲'String' – Nishant 2011-03-02 17:59:58

回答

1

而不是使用一個數組,你想使用Map()

Customer myCust = customers.get(search); 

另一種選擇是創建一個新的客戶

Customer searchCust = new Customer(search); 

place = Arrays.binarySearch(A,searchCust); 

要找到正確的客戶的最後一節,您需要實現Comparable界面:

        // add this 
public class Customer implements Comparable<Customer> { 

    // add this guy 
    public int compareTo(Customer other) { 
     return this.name.compareTo(other.name); // I'm assuming 'name' is the variable of the name 
    } 

} 

或者您可以使用在@ spinttheblack的帖子中定義的比較器。

+0

我有使用數組。這是我的Java類的一個任務。 :/我會嘗試製作一個新的客戶。謝謝。 – Lish 2011-03-02 18:00:40

+0

這樣做!謝謝! – Lish 2011-03-02 18:02:52

+0

我的想法很多,這就是爲什麼我在那裏放兩個選項。請記住,您需要重寫客戶中的「公共布爾等於(Object o)」方法才能工作。否則,它會做參考比較,它不會工作。 – corsiKa 2011-03-02 18:03:06

1

看起來您正在傳入一個Customer數組並搜索一個字符串。

除了glowcoder的解決方案(創建一個虛擬Customer),您可能需要重寫Customer的compareTo方法。即,

class Customer{ 
    compareTo(Object o1, Object o2){ 
      return ((Customer)o1).getStringField().compareTo(((Customer)o2).getStringField()) 
    } 
}