简体   繁体   English

如何在Java中的搜索函数(数组)中返回多个值

[英]How to return multiple values within a search function(array) in Java

I have a search function in a class that searches through an array by a String(Department of work) and a count. 我在一个类中有一个搜索功能,该功能通过一个String(工作部门)和一个计数来搜索数组。 In the main the program will ask the user what category does he/she wants to search for. 在主程序中,程序将询问用户他/她想要搜索什么类别。 Example: library ; 示例:library; the program should give all the books that are in that specific department (there is a function that lets the user add books) The problem is that the program only returns one book and not the all the books that are associated within that Category. 该程序应提供该特定部门中的所有书籍(有一个功能可以让用户添加书籍)问题是该程序仅返回一本书,而不返回该类别中关联的所有书籍。

Your function should not return an single index it should return a collection of indexes. 您的函数不应返回单个索引,而应返回索引的集合。 For example. 例如。

public static Collection<Integers> Searchdep(EmployeeClass EmployeeArr[], String department, int size)  {
   List<Integer> intList = new ArrayList<Integer>();
   for(int i=0; i<size; i++)
   {
      if(EmployeeArr[i].Department.equals(department)) {
          intList.add(i);
      }
   }
   return intList;
}

Then in your main check for size of the collection, if it is zero that mean nothing was found. 然后在您的主检查中检查集合的大小,如果为零,则表示未找到任何内容。 Theses the line need to change 论文行需要改变

index=EmployeeClass.SearchDep(EmpList,department,count);
JOptionPane.showMessageDialog(null,index);

to

Collection<Integer> returnedCollection = EmployeeClass.SearchDep(EmpList,department,count);
if(returnedCollection.isEmpty()){
   JOptionPane.showMessageDialog(null,"Nothing was found");     
} else {
   StringBuilder  str = new StringBuilder();
   for(Integer integer: returnedCollection){
       str.appened(EmpList[integer].ReturnStringInfo());
       str.appened(", ");
   }
   JOptionPane.showMessageDialog(null,"Indexed are : "+ str.toString());     
}

Just return an array of indices instead of a single index. 只需返回索引数组而不是单个索引即可。 For example: 例如:

public static List<Integer> Searchdep(EmployeeClass EmployeeArr[], String department, int size){
      List<Integer> result = new ArrayList<Integer>();
      for(int i=0; i<size; i++){
          if(EmployeeArr[i].Department.equals(department)){
              result.add(i);
          }
      }
      return result;
}

The best option here is to pass a Visitor action to apply to each employee found. 最好的选择是通过“访客”操作以应用于找到的每个员工。 In Java 8, this would be a lambda but in Java 6 or 7 this would be an anonymous inner class. 在Java 8中,这将是lambda,但在Java 6或7中,这将是匿名内部类。

Then you might return the count found so you can detect when there was no matches. 然后,您可能会返回找到的计数,以便可以检测何时没有匹配项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM