Click to See Complete Forum and Search --> : searching


newbiesmith
March 18th, 2003, 03:13 PM
hey...

i wondering could anyone point me in the direction of a good explaination / sample code on linear searching....i need to search through an array of leads based on a name entered into a textfield....the array is created in a separate class...my code is below:

search = searchFld.getText();

for (int i = 0; !(leads[i].getCustomer().equals(search)) &&
!(leads[i] = leads[leads.length-1]); i++){}

if (leads[i] = leads[leads.length-1]){
System.out.println("Name not found");
}
else
{
System.out.println("Name is: "+leads[i].getCustomer());
}

Thanks

Goodz13
March 18th, 2003, 04:02 PM
search = searchFld.getText();

for (int i = 0; !(leads[i].getCustomer().equals(search)) && !(leads[i] = leads[leads.length-1]); i++){}

if (leads[i] = leads[leads.length-1]){
System.out.println("Name not found");
}
else
{
System.out.println("Name is: "+leads[i].getCustomer());
}


The above code could work, but your "i" has gone out of scope.

// here
if (leads[i] = leads[leads.length-1]){
one way you could do it, is to declare "i" outside of the "for" loop.

...And the single equals sign


// here
!(leads[i] = leads[leads.length-1])

// and
if (leads[i] = leads[leads.length-1]){



...are assiging the values, not comparing. Try using ==

better yet, for your for loop, try something like

for (i = 0; !(leads[i].getCustomer().equals(search)) && i < leads.length; i++){}



Then you should think about:
-Should it be case sensitive
-Should the search match the whole string
-Should you allow the user to enter wildcards.

dlorde
March 18th, 2003, 07:15 PM
A simpler solution would be to use something like a Hashtable (http://java.sun.com/j2se/1.4/docs/api/java/util/Hashtable.html), where you can store your lead objects keyed by the customer name, and retrieve them by customer name.

Alternatively, if you need to use an array, you could take advantage of the utilities in the Arrays (http://java.sun.com/j2se/1.4/docs/api/java/util/Arrays.html) class. This allows you to do a binarySearch(...) on a sorted array, and supplies a sort(...) method to do that too... All they require is that either your Lead objects implement the Comparator (http://java.sun.com/j2se/1.4/docs/api/java/util/Comparator.html) interface, or that a simple Comparator object is supplied.

I think Hashtable is simplest, but if you're interested, I can provide example code for the sort and binary search.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them...
Laurence J. Peter

dlorde
March 19th, 2003, 12:12 PM
OK, I knocked up a simple example showing both the Hashtable search and the Arrays search techniques. The latter is not so elegant as it requires a dummy Lead to be created to search with, and it sorts the array (although this won't matter if it's already sorted, or needs to be sorted anyway). If you're prepared to have your Lead class implement Comparable (i.e. add a 'compare(...)' method), you can leave out the creation of the Comparator and call the Arrays methods without it. Alternatively you could create an external 'LeadCustomerComparator' (or whatever) class, so it could also be used elsewhere. But unless your lead array is really huge, the Hashtable solution looks easiest...import java.util.*;
/**
* Creates array of Leads with customer values 'Name20' to
* 'Name1' and corresponding ID values (20, 19, 18... 1).
* Pass a customer string as a command-line argument to
* search for.
*/
public class SearchLeads {
private static int NUM_LEADS = 20; // Size of dummy Leads array

public static void main(String[] args) {
try {
// Get search string from command line
if (args.length == 0) {
throw new Exception("You didn't enter a search argument!");
}
String search = args[0];

// get the leads to search
Lead[] leads = getLeads();

// Search array using a Hashtable
Lead found = findWithHashtable(leads, search);
System.out.println("\nFound with Hashtable: " + found);

// Search array using Arrays class methods
found = findWithArraysUtils(leads, search);
System.out.println("Found with Arrays utils: " + found);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}

// Create dummy array of leads to search
private static Lead[] getLeads() {
System.out.println("Leads array:");
Lead[] leads = new Lead[NUM_LEADS];
for (int i = 0; i < NUM_LEADS; i++) {
int id = NUM_LEADS - i;
leads[ i ] = new Lead("Name" + id, id);
System.out.println(leads[ i ]);
}
return leads;
}

private static Lead findWithHashtable(Lead[] leadArray, String search) {
Hashtable leads = new Hashtable();

// Put leadArray into Hashtable keyed by customer
for (int i = 0; i < leadArray.length; i++) {
Lead lead = leadArray[ i ];
leads.put(lead.getCustomer(), lead);
}
// Retrieve entry keyed by search string
return (Lead)leads.get(search);
}

private static Lead findWithArraysUtils(Lead[] leadArray, String search) {
// Create a dummy Lead to search for (this is a potential drawback)
Lead searchLead = new Lead(search, 0);

Lead found = null;

// Get the Comparator to compare the Leads
Comparator leadComparator = getLeadComparator();

// sort the array by customer
Arrays.sort(leadArray, leadComparator);

// search the array for the index of the searchLead
int index = Arrays.binarySearch(leadArray, searchLead, leadComparator);

if (index >= 0) {
found = leadArray;
}
return found;
}

// create Comparator to compare Lead customers
private static Comparator getLeadComparator() {
Comparator leadComparator = new Comparator() {
public int compare(Object o1, Object o2) {
Lead lead1 = (Lead)o1;
Lead lead2 = (Lead)o2;
return lead1.getCustomer().compareTo(lead2.getCustomer());
}
};
return leadComparator;
}

}

/**
* Example Lead class with customer and ID
*/
class Lead {
String customer;
int id;

public Lead(String name, int id) {
this.customer = name;
this.id = id;
}

public int getId() {
return id;
}

public String getCustomer() {
return customer;
}

public String toString() {
return "Customer = '" + getCustomer() + "', id = " + getId();
}
}
[i]I love the smell of fresh code in the morning...

Metaphor
March 19th, 2003, 06:52 PM
You are disgustingly verbal in your answers, Dave. ;) That's a grossly big example, elaborating on such small code to begin with. Good! But big. :)

To explain: I'm not berating, or complaining. Just...noting. Maybe I shouldn't do that. I don't know.

dlorde
March 20th, 2003, 10:22 AM
It's only 'big' because it's a full test rig. I thought it might be useful to someone trying to evaluate the two techniques. The relevant code is in the two methods findWithHashtable(...) and findWithArraysUtils(...).

I'm not berating, or complaining. Just...noting.Hmm, the use of emotionally loaded adjectives such as "disgustingly" and "grossly" might suggest otherwise - or is that just a subconscious bias?

A designer knows he's achieved perfection not when there is nothing left to add, but when there is nothing left to take away...
A. de Saint-Exupery

Metaphor
March 20th, 2003, 10:25 AM
I think it's merely a subconscious love for loaded words. ;) If I've managed to - somehow - offend, I apologize, because that was certainly not my intention. I am merely amazed at the richness of your answers. And no, I'm not a stalker. Nope. Not even close. ;)

dlorde
March 21st, 2003, 07:06 AM
If I've managed to - somehow - offend, I apologize :p No, I wasn't really offended, just a bit puzzled by the unusual adjectives used...

And no, I'm not a stalker. Nope. Not even close. ;) :confused: who said anything about stalking?

That sounds so very much nastier than it is...
adam

Metaphor
March 21st, 2003, 07:11 AM
who said anything about stalking?

Not me, nope, nuh uh.

Seriously though. Some people might, MIGHT I say, consider these posts a sort of stalking, or whatever. People are odd. Just 'splaining myself. :)

Ignore these last few posts! Erase them from your memory! I'll return to my usual, bitter and cynical self within a few days.

And, as far as hashtables go...wohoo! Love them!

dlorde
March 21st, 2003, 07:20 AM
as far as hashtables go...wohoo! Love them!Not that kind of hashtable... (ssss, toke... :cool: )

It's nice to be loved, but there's a lot to be said for CRINGING RESPECT...
Anon

newbiesmith
March 21st, 2003, 12:24 PM
thanks dlorde for your comprehensive example:

I now have another problem:

if(e.getSource() == searchBtn){

searchname = searchFld.getText();
var = my.searchArray(searchname);

}


public Lead searchArray(String surname){

for(int counter = 0; counter<10; counter++){
if (leads[counter].aCustomer.getSurName().equals(surname)){
System.out.println("Success!");
return leads[counter];
}


}
}

the compiler claims i'm missing a return statement?

Goodz13
March 21st, 2003, 12:35 PM
public Lead searchArray(String surname){

for(int counter = 0; counter<10; counter++){
if (leads[counter].aCustomer.getSurName().equals(surname)){
System.out.println("Success!");
return leads[counter];
}
}
}


In the code above, if ...getSurName().equals(surname) isn't true, the method won't return anything. You might want to do somewthing like this.

public Lead searchArray(String surname){
Lead leadRet = null;
for(int counter = 0; counter<10; counter++){
if (leads[counter].aCustomer.getSurName().equals(surname)){
System.out.println("Success!");
leadRet = leads[counter];
break;
}
}
return leadRet;
}

newbiesmith
March 21st, 2003, 01:04 PM
i now have a null pointer exception at :


leadCount = 0;

leadCount = my.createLead(firstname, surname, address1, address2, address3);
noLeadsFld.setText(Integer.toString(leadCount));


this is my call to the class where i have my search...

Goodz13
March 21st, 2003, 05:08 PM
You'd have to check to make sure that the returned Lead from searchArray(...) isn't null before you try to use the returned Lead.

If the search fails(It didn't find it), then the return would be null.

newbiesmith
March 22nd, 2003, 07:59 AM
You see i'm creating the lead in 1 screen and trying to return the info from that lead from another screen based on the surname...why would i get a null pointer exception if i entered say smith and then tried to return the info based on 'smith'?

dlorde
March 22nd, 2003, 10:58 AM
A nullPointerException usually only refers to a single line, and it usually indicates the variable that has caused the exception (if a variable is involved).

Can you post the exact line referred to by the nullPointerException you get, and the variable name, if present?

In defeat unbeatable: in victory unbearable...
Winston Churchill

newbiesmith
March 24th, 2003, 05:33 AM
I found it - hours later! Such a relief...thanks guys for all your help...really appreciated!