1

Sorry if this is a repeat, but I've been looking for an answer to this question, but I can't find one anywhere and my last question was for the same code but with a different problem.

I need to find a string inside an array, but all the Strings in the array are 16 characters long and the search key will not be 16 characters when entered by the user. Every attempt I've made at this thus far has ended with the String not being found, though I know it is in the array. I think it has something to do with the trailing spaces after the actual string text in the array, but I'm not sure how to handle it.

This is my search statement so far. I'll note that my compareTo() statement does compare this.name to other.name, so I'm quite confused.:

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);

      Customer searchCust = new Customer(search);

      place = Arrays.binarySearch(A,searchCust);

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


 public int compareTo(Customer a)
 {
  return this.name.compareTo(a.name);
 }   //end compareTo
6
  • 1
    Pls, provide A declaration. Commented Mar 2, 2011 at 20:38
  • @pst I just added search = search.replaceAll("(\\r|\\n)", ""); and it didn't change my results any. I feel like I'm still missing something pretty huge here. :/ Commented Mar 2, 2011 at 20:38
  • @Stas It's an array of String, double, float (respectively) read in from a file. All strings are 16 characters due to a delimiter statement when read into the array. Commented Mar 2, 2011 at 20:42
  • Just out of interest - how exactly are you doing your name comparison check? Using the String equals method or the == operator? Commented Mar 2, 2011 at 20:43
  • @Lish: You should probably post the relevant portions of your Customer class. Particularly compareTo and equals. Commented Mar 2, 2011 at 20:44

5 Answers 5

1

Edit: after clarification of the question.

So, the problem is that your users are entering something like

"Smith"
but your array elements are always padded to 16-characters long and might have the search term somewhere in the middle, like
"John Smith      "
then I would recommend just looping through the array and doing a .contains() on each element.

Binary search is an optimization which I would only consider if performance shows itself to be a problem, because it introduces quite a lot of complication.

Sign up to request clarification or add additional context in comments.

4 Comments

But what would happen if the user searches for a last name rather than a first? It would still be comparing two non-identical strings, wouldn't it? :/
so you want "Smith" to match on "John Smith " (6 spaces at the end)? - This changes the question a bit, because I don't think it would be natural to use compareTo in this case (they're not really equal).
For simplicity, I'd just loop through the array and do a .contains() test on each element - you'd only want to optimise to a binary search if performance shows itself to be a problem.
I WOULD TOTALLY HUG YOU IF I COULD! This totally fixed my issue. Thanks so much!
1

Okay, if binary search isn't possible (which seems to be the case), we can just implement a simple custom solution:

public Customer findCustomerByName(Customer[] array, String pattern){
    for(Customer candidate: array){
       if(candidate.getName().contains(pattern)){
          return candidate;
       }
    }
    return null;
}

Or did I miss something?

Comments

0

If your search key is different from your array values your binary search wont find a match using compareTo - if as you say you've implemented it to do a plain old String equality check.

There's another implementation fo binarySearch that takes a custom Comparator object...

public static int binarySearch(Object[] a,
                               Object key,
                               Comparator c)

You could implement your own custom Comparator to match the shortened key to the array value.

Comments

0

Or you make your class Customer implement Comparable (see Comparable). Then you implement int compareTo(Customer otherCustomer) inside Customer, where you return <0, 0 or >0 number, depending on whether otherCustomer should be less, equal, greater than this (the current object).

As taken from Arrays.sort:

All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

1 Comment

Ohh. I did something similar in a previous lab. In that case, would I need to replace return this.name.compareTo(a.name); with that statement so it doesn't overlap?
0

My notes:

  1. Make sure Customer correctly implements natural ordering (aka Comparable) or;

  2. Use the version of binarySearch that takes a Comparator (http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html) and;

  3. Verify the input is as expected (e.g. it contains no extra new-line character, etc) and;

  4. Make sure A is of the correct type -- Customer[] in this case (the declaration is not given). binarySort(string[], Customer) will never succeed. (If using the version of binarySort that takes a Comparator a mismatch like this would not compile.)

Happy coding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.