2017-02-27 71 views
0

我正在开发一种搜索算法。其中我们有一个学生对象的ArrayList。我们必须从ArrayList中搜索学生。学生班的属性是姓名,城市,国家和电话号码。搜索应该起作用,如果我们输入姓名,城市,国家或号码,我们应该得到与搜索匹配的学生对象列表。 soppose,如果我们在搜索中键入“john”,那么我们应该得到名称为john的学生对象列表。如果搜索查询有多个单词(如“约翰巴西”),那么我们应该得到名称为约翰和国家的所有学生对象的列表是巴西。我没有得到正确的输出,在列表中,我得到了名称为john的所有对象以及该国为巴西的所有对象。获取(名称||国家),但我需要(名称& &国家)。任何帮助将不胜感激。提前致谢。使用多词搜索键搜索存储在arraylist中的对象

的代码如下:

public Class Student { 
    private String first_name; 
    private String last_name; 
    private String city; 
    private String country; 
    private int phone_number; 
} 

public ArrayList<Student> searchMethod() { 

    ArrayList<Student> initial_result_list= new ArrayList<Student>; 

    for (Student student : student_list) { 
     for (String search : array_of_search_words) { 
      if((null!=student.getName() && student.getName().contains(search)) 
      || (null!=student.getCity() && student.getCity().contains(search)) 
      || (null!=student.getCountry() && student.getCountry().contains(search)) 
      || (null!=student.getCity() && student.getCity().contains(search)) 
      || (null!=student.getPhone_number() && student.getPhone_number().contains(search))) { 

       if(!initial_result_list.contains(student)) { 
        initial_result_list.add(student); 
       } 
      } 
     } 
    } 
    return initial_result_list; 
} 

回答

0

你必须确保在array_of_search_words每个词语已被一些Class Student的属性相匹配。

对于这种改变你的逻辑:

for (Student student : student_list) { 
    bool matched = false; 
    for (String search : array_of_search_words) { 
     if((null!=student.getName() && student.getName().contains(search)) 
     || (null!=student.getCity() && student.getCity().contains(search)) 
     || (null!=student.getCountry() && student.getCountry().contains(search)) 
     || (null!=student.getCity() && student.getCity().contains(search)) 
     || (null!=student.getPhone_number() && student.getPhone_number().contains(search))) {  
     matched = true;   
     } 
     else {matched = false;break;} 

    } 
    if(!initial_result_list.contains(student) && matched) 
       initial_result_list.add(student); 
} 
+0

非常感谢sumeet ..你的方法奏效! – Dipanshu