[英]How to return multiple values within a search function(array) in Java
我在一個類中有一個搜索功能,該功能通過一個String(工作部門)和一個計數來搜索數組。 在主程序中,程序將詢問用戶他/她想要搜索什么類別。 示例:library; 該程序應提供該特定部門中的所有書籍(有一個功能可以讓用戶添加書籍)問題是該程序僅返回一本書,而不返回該類別中關聯的所有書籍。
您的函數不應返回單個索引,而應返回索引的集合。 例如。
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中,這將是匿名內部類。
然后,您可能會返回找到的計數,以便可以檢測何時沒有匹配項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.