开发者

Searching multi-dimensional arrays for a String

I have an array with types String, double, and float, and I need to be able to search for a String in it. I tried to do a binary search, but I'm getting the following error when I run the program and attempt a search:

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)

I haven't found any other methods for searching a 3d array, so any help would be greatly appreciated.

Here is my code:

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);开发者_Go百科
     else
     {
       System.out.println("Customer found:");  
       System.out.println(A[place]);
     }

            break;


Rather than using an array, you would want to use a Map()

Customer myCust = customers.get(search);

Another option would be to create a new Customer

Customer searchCust = new Customer(search);

place = Arrays.binarySearch(A,searchCust);

For the last section to find a customer correctly, you'll need to implement the Comparable interface:

                                 // 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
    }

}

or you can use the Comparator defined in @spinttheblack's post.


It looks like you're passing in an array of Customer and searching for a string.

In addition to glowcoder's solution (create a dummy Customer), you'll likely need to override the compareTo method of Customer. I.e.,

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜