?
Solved

keyword search

Posted on 2003-02-26
16
Medium Priority
?
241 Views
Last Modified: 2010-03-31
Hi:
The following programs works but I want to be able to search the array using a single keyword(ex: Keyword key = new Keyword("WilliamF");)
Is this possible? And how would I accomplish the task?


import java.util.*;
public class StudentReports
{ public static void main(String args[])
{
// small array of students for testing
Student people[] = {new Student("William", "F"),
new Student("Charles", "D"),
new Student("Ernest", "P"),
new Student("Ursula", "H"),

new Student("Emily", "J")};

Comparator FirstComp = new FirstNameComp();
Arrays.sort(people, lastComp);
for (int i = 0; i < people.length; i++)
System.out.println(" " + people<i>);
System.out.println();

Student key = new Student("William","H");
int w =  Arrays.binarySearch(people,key,firstComp);
     
System.out.println(people[w]);

}
}



public class Student {
String firstName;
String lastName;

public Student(String first, String last) {
firstName = first;
lastName = last;

}

public String toString() {
return firstName + " " + lastName;
}
}


import java.util.Comparator;
public class FirstNameComp implements Comparator {
public int compare(Object obj1, Object obj2) {
Student student1 = (Student) obj1;
Student student2 = (Student) obj2;
return student1.firstName.compareTo(student2.firstName);
}

} import java.util.*;
public class Keyword{
 
  String key;
    public Keyword(String key) {
   
    this.key = key;
   
  }

 public String getKey()
   {
      return key;
   }
 
}


0
Comment
Question by:LearningJava
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 3
  • 3
  • +1
16 Comments
 
LVL 92

Expert Comment

by:objects
ID: 8030298
1. your comparator needs to know how to compare Student and Key objects, as well as comparing Students to Students.
2. your array needs to be sorted using the same comparator.
0
 
LVL 3

Expert Comment

by:allahabad
ID: 8030733
I have modified StudentReports,Student,FirstNameComp,LastNameComp classes,
and have added NameComp class to search on "William F".

Run the StudentReports class. I have provided three options; search by first Name,search by last Name and search by first Name and last Name.

Hope this helps.

-------
import java.util.*;
import java.io.*;
public class StudentReports{


   public static void main(String args[]) throws IOException {
      // small array of students for testing
      Student people[] = {new Student("William", "F"),
                        new Student("Charles", "D"),
                        new Student("Ernest", "P"),
                        new Student("Ursula", "H"),
                        new Student("Emily", "J")};

      BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Search Option :");
      System.out.print("\n");
      System.out.print("1-->First Name ");
      System.out.print("\n");
      System.out.print("2-->Last Name ");
      System.out.print("\n");
      System.out.print("3-->Full Name(FirstName LastName ");
      System.out.print("\n");
      System.out.print("Select Option :");
      String y = stdin.readLine();
      int option = Integer.parseInt(y);
      switch(option){

         case 1:
            System.out.print("Enter First Name ");
            String fName= stdin.readLine();
            String found = searchOnFirstName(people,fName);
            if (found != null){
               System.out.println("Name Found " + found);
            }
            else
               System.out.println("No name found matching to the first name entered");
            return;
         case 2:
            System.out.print("Enter Last Name ");
            String lName= stdin.readLine();
             found = searchOnLastName(people,lName);
            if (found != null){
               System.out.println("Name Found " + found);
            }
            else
              System.out.println("No name found matching to the last name entered");
            return;
          case 3:
               System.out.print("Enter  Name ");
               String name= stdin.readLine();
               found = searchOnName(people,name);
               if (found != null){
                  System.out.println("Name Found " + found);
               }
               else
                  System.out.println("Name Not Found ");
               return;
          default:
               System.out.println("Invalid Option");


      }

   }

   private static String searchOnFirstName(Student[] stu,String key){

      Comparator firstComp = new FirstNameComp();

      Arrays.sort(stu,firstComp);
      Student nameKey = new Student();
      nameKey.setFirstName(key);

      int pos =  Arrays.binarySearch(stu,nameKey,firstComp);
      if (pos <0){

         return null;

      }
      else return stu[pos].toString();

   }

   private static String searchOnLastName(Student[] stu,String key){

       Comparator lastComp = new LastNameComp();

       Arrays.sort(stu,lastComp);
       Student nameKey = new Student();
       nameKey.setLastName(key);

       int pos =  Arrays.binarySearch(stu,nameKey,lastComp);

       if (pos <0){

          return null;

       }
       else
         return stu[pos].toString();

   }
   private static String searchOnName(Student[] stu,String key){

        StringTokenizer token = new StringTokenizer(key," ");
        if (token.countTokens() != 2){
            System.out.println("Error:Please enter Firstname and Lastname like William F");
            return null;
        }

        Student nameKey = new Student();
        nameKey.setFirstName(token.nextToken());
        nameKey.setLastName(token.nextToken());

        Comparator nameComp = new NameComp();
        Arrays.sort(stu,nameComp);

        int pos =  Arrays.binarySearch(stu,nameKey,nameComp);

        if (pos <0){

           return null;

        }
        else
         return stu[pos].toString();

   }
}
----------------

public class Student {
   String firstName;
   String lastName;

   public Student(String first, String last) {
      firstName = first;
      lastName = last;

   }

   public Student(){
      firstName = "";
      lastName ="";
   }
   public void setLastName(String lastName){
      this.lastName = lastName;
   }
   public void setFirstName(String firstName){
         this.firstName = firstName;
   }

   public String toString() {
      return firstName + " " + lastName;
   }
   public String getFirstName(){
      return this.firstName;
   }
   public String getLastName(){
         return this.lastName;
   }

}
--------------------

import java.util.Comparator;
public class FirstNameComp implements Comparator {
   public int compare(Object obj1, Object obj2) {
      Student student1 = (Student) obj1;
      Student student2 = (Student) obj2;
      return student1.firstName.compareTo(student2.firstName);
   }

}
---------------------
import java.util.Comparator;
public class LastNameComp implements Comparator {
   public int compare(Object obj1, Object obj2) {
      Student student1 = (Student) obj1;
      Student student2 = (Student) obj2;
      return student1.lastName.compareTo(student2.lastName);
   }

}
---------------------
import java.util.Comparator;
public class NameComp implements Comparator {
   public int compare(Object obj1, Object obj2) {
      Student student1 = (Student) obj1;
      Student student2 = (Student) obj2;
      return ((student1.lastName)+" "+(student1.firstName)).compareTo(((student2.lastName)+" " +(student2.firstName)));
   }

}

0
 
LVL 92

Expert Comment

by:objects
ID: 8030793
Thats not really what the question asks.

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Expert Comment

by:allahabad
ID: 8030881
objects:
You are right. But, we had already answered a question http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20527814.html for LearningJava. I am thinking , this is what is looking for.  I may be wrong.

Regards
SK
0
 
LVL 92

Expert Comment

by:objects
ID: 8030916
understood, thanks.
0
 

Author Comment

by:LearningJava
ID: 8032812
Thanks for the help.

I did try to modify my code from the previous post with the following code but I could not get the code to work. Could you please share your thoughts on the code below.

Thanks.

1. Search by name:-
    Arrays.binarySearch(data,key, new Comparator() {
       public int compare(Object o1, Object o2) {
           int idx1 = ((String)o1).indexOf(",");
            int idx2 = ((String)o2).indexOf(",");
            return ((String)o1).substring(idx1).compareTo(((String)o2).substring(idx2));
       }
       public boolean equals(Object obj) {
           int idx1 = ((String)o1).indexOf(",");
           int idx2 = ((String)o2).indexOf(",");
           return ((String)o1).substring(idx1).equals(((String)o2).substring(idx2));
       }
    });

2. Search by Phone Number:-
    Arrays.binarySearch(data,key, new Comparator() {
       public int compare(Object o1, Object o2) {
           int idx1 = ((String)o1).indexOf(",");
            int idx2 = ((String)o2).indexOf(",");
            return ((String)o1).substring(0, idx1).compareTo(((String)o2).substring(0, idx2));
       }
       public boolean equals(Object obj) {
           int idx1 = ((String)o1).indexOf(",");
           int idx2 = ((String)o2).indexOf(",");
           return ((String)o1).substring(0, idx1).equals(((String)o2).substring(0, idx2));
       }
    });

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8033203
It's difficult to say about your code without seeing it in context, but your Comparators shouldn't have to implement equals under normal circumstances.

I've modified your code to do a search by Keyword as you requested. It can be compiled in one file, so just save it to a new directory while you're examining it. You should provide accessors/mutators like you've partially done with Keyword and fix up the indentation:

import java.util.*;

public class StudentReports
{ public static void main(String args[])
{
// small array of students for testing
Student people[] = {new Student("William", "F"),
new Student("Charles", "D"),
new Student("Ernest", "P"),
new Student("Ursula", "H"),

new Student("Emily", "J")};

Comparator firstComp = new FirstNameComp();
Arrays.sort(people, firstComp);
for (int i = 0; i < people.length; i++)
System.out.println(" " + people[i]);
System.out.println();

Student key = new Student("William","H");
int w =  Arrays.binarySearch(people,key,firstComp);

System.out.println(people[w]);

/*
 * Use your new Keyword style search
 */

 // Construct keyword first
 Keyword kw = new Keyword("WilliamF");

 // Create the KeywordComparator
 Comparator keywordComparator = new KeywordComparator();

 // Search for keyword in above *sorted* array
 int foundIndex = Arrays.binarySearch(people, kw, keywordComparator);

 if (foundIndex >= 0) {
   System.out.println("Keyword '" + kw + "' found in array at index " + foundIndex);
 }
 else {
   System.out.println("Keyword '" + kw + "' not found in array");
 }

}
}



class Student {
String firstName;
String lastName;

public Student(String first, String last) {
firstName = first;
lastName = last;

}

public String toString() {
return firstName + " " + lastName;
}
}



class FirstNameComp implements Comparator {
public int compare(Object obj1, Object obj2) {
Student student1 = (Student) obj1;
Student student2 = (Student) obj2;
return student1.firstName.compareTo(student2.firstName);
}

}

//import java.util.Comparator;
class Keyword {

 String key;
   public Keyword(String key) {

   this.key = key;

 }

public String getKey()
  {
     return key;
  }

  public String toString() {
    return key;
  }

}

class KeywordComparator implements Comparator {

  public int compare(Object obj1, Object obj2) {
    Student student = (Student) obj1;
    Keyword keyword = (Keyword) obj2;
    return (student.firstName + student.lastName).compareTo(keyword.getKey());
  }

}
0
 

Author Comment

by:LearningJava
ID: 8036935
Hi:
    I tried the program and it works fine but I need to take the program a step further. If the keyword = William rather then WilliamF then the program returns that William was not found. How can solve this problem so that William is found?


Keyword kw = new Keyword("William");



0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8036959
Then you would change

return (student.firstName + student.lastName).compareTo(keyword.getKey());


to

return (student.firstName).compareTo(keyword.getKey());

Do you understand how this is working?


0
 
LVL 92

Expert Comment

by:objects
ID: 8036993
> I've modified your code to do a search by Keyword as you requested.

And as I specified :-)
0
 
LVL 92

Expert Comment

by:objects
ID: 8037003
> How can solve this problem so that William is found?

Can you define exactly how you would like your keyword search to work?
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 8037035
Well it seemed to me he needed to see some code objects, especially since incorrect code had already been produced.
0
 
LVL 92

Expert Comment

by:objects
ID: 8037111
> Well it seemed to me he needed to see some code

Need more details on the requirements before code can be produced :)
0
 
LVL 3

Expert Comment

by:allahabad
ID: 8037119
Did you run my program;  run it  and use option 1 to serach for "Wiiliam" (search on first name). It also has  two other options,  option 2 is search for last name( like F), and 3 is  for the  first name last name like (Wiiliam F).
0
 

Author Comment

by:LearningJava
ID: 8037505
That fix was so obvious when I took a closer look at the code.

You are an expert!!

Thanks again.
0
 
LVL 92

Expert Comment

by:objects
ID: 8037564
That code just does virtually the same as your original code (ie. search on first name), it just wraps the first name in a Keyword class.
But if thats what you wanted...
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month8 days, 5 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question