【问题标题】:How to return multiple values within a search function(array) in Java如何在Java中的搜索函数(数组)中返回多个值
【发布时间】:2014-10-06 13:12:08
【问题描述】:

我在一个类中有一个搜索函数,它通过一个字符串(工作部门)和一个计数来搜索一个数组。 在主程序中,程序将询问用户他/她想要搜索什么类别。示例:库;该程序应该提供该特定部门的所有书籍(有一个功能可以让用户添加书籍) 问题是程序只返回一本书,而不是该类别中关联的所有书籍。

【问题讨论】:

  • 您考虑过返回List吗?

标签: java arrays search indexing


【解决方案1】:

您的函数不应返回单个索引,而应返回索引集合。 例如。

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;
}

然后在你的主要检查集合的大小,如果它为零,则意味着没有找到任何东西。 这些线需要改变

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

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());     
}

【讨论】:

  • 但结果将显示为索引,即员工所在的数字,而不是员工信息。所以它应该类似于 Emplist[indexes that we have].ShowInfoToUser();但是怎么可能把它和你所做的结合起来呢?
  • 它给出一个错误,说它不能在数组上调用 get(integer)
【解决方案2】:

只返回一个索引数组而不是单个索引。例如:

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;
}

【讨论】:

    【解决方案3】:

    这里的最佳选择是传递访客操作以应用于找到的每个员工。在 Java 8 中,这将是一个 lambda,但在 Java 6 或 7 中,这将是一个匿名内部类。

    然后您可能会返回找到的计数,以便您可以检测何时没有匹配项。

    【讨论】:

      猜你喜欢
      • 2013-02-19
      • 2013-08-29
      • 2021-05-13
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 2011-06-06
      • 2017-10-09
      • 2011-06-12
      相关资源
      最近更新 更多