Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 242
  • Last Modified:

keyword search

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
LearningJava
Asked:
LearningJava
  • 7
  • 3
  • 3
  • +1
1 Solution
 
objectsCommented:
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
 
allahabadCommented:
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
 
objectsCommented:
Thats not really what the question asks.

0
Independent Software Vendors: 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!

 
allahabadCommented:
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
 
objectsCommented:
understood, thanks.
0
 
LearningJavaAuthor Commented:
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
 
CEHJCommented:
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
 
LearningJavaAuthor Commented:
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
 
CEHJCommented:
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
 
objectsCommented:
> I've modified your code to do a search by Keyword as you requested.

And as I specified :-)
0
 
objectsCommented:
> How can solve this problem so that William is found?

Can you define exactly how you would like your keyword search to work?
0
 
CEHJCommented:
Well it seemed to me he needed to see some code objects, especially since incorrect code had already been produced.
0
 
objectsCommented:
> Well it seemed to me he needed to see some code

Need more details on the requirements before code can be produced :)
0
 
allahabadCommented:
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
 
LearningJavaAuthor Commented:
That fix was so obvious when I took a closer look at the code.

You are an expert!!

Thanks again.
0
 
objectsCommented:
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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 7
  • 3
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now