【发布时间】:2014-10-06 13:12:08
【问题描述】:
我在一个类中有一个搜索函数,它通过一个字符串(工作部门)和一个计数来搜索一个数组。 在主程序中,程序将询问用户他/她想要搜索什么类别。示例:库;该程序应该提供该特定部门的所有书籍(有一个功能可以让用户添加书籍) 问题是程序只返回一本书,而不是该类别中关联的所有书籍。
【问题讨论】:
-
您考虑过返回
List吗?
标签: java arrays search indexing
我在一个类中有一个搜索函数,它通过一个字符串(工作部门)和一个计数来搜索一个数组。 在主程序中,程序将询问用户他/她想要搜索什么类别。示例:库;该程序应该提供该特定部门的所有书籍(有一个功能可以让用户添加书籍) 问题是程序只返回一本书,而不是该类别中关联的所有书籍。
【问题讨论】:
List吗?
标签: java arrays search indexing
您的函数不应返回单个索引,而应返回索引集合。 例如。
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());
}
【讨论】:
只返回一个索引数组而不是单个索引。例如:
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;
}
【讨论】:
这里的最佳选择是传递访客操作以应用于找到的每个员工。在 Java 8 中,这将是一个 lambda,但在 Java 6 或 7 中,这将是一个匿名内部类。
然后您可能会返回找到的计数,以便您可以检测何时没有匹配项。
【讨论】: