构建我自己的顺序搜索方法,由于某种原因,我只能让int搜索工作,而不是String。正在搜索的列表是从.csv文件构建的,并且每次一行读取该文件,每行包含一个对象的所有数据。从对象列表中提取一个2d数组,只包含它们的名称和ID,顺序搜索只搜索这些名称&id。我在调试器中运行它,正在搜索的数组值确实显示(在names[4][0]中),但它不返回true,而是继续返回false。int搜索返回true,因为它应该在正确的位置。下面是顺序搜索代码:
package Contributors;
public class SequentialSearch {
//search for name match
static boolean contains(String[][] names, String nameSearched){
for (String[] name : names) {
if (name[0].equalsIgnoreCase(nameSearched)) {
return true;
}
}
return false;
}
//search for ID match
static boolean contains(String[][] names, int idSearched){
for(int loop = 0; loop<names.length; loop++){
if(Integer.parseInt(names[loop][1]) == idSearched){
return true;
}
}
return false;
}
}
下面是构建2d数组的类:
public class SearchArray {
String[][] nameSearch(List sortedList){
String[][] sortedNames = new String[sortedList.size()][2];
Contributor current;
String currentName;
String currentID;
//loop to add each name and ID field to a 2d array
for(int copy = 0; copy < sortedList.size(); copy++){
current = (Contributor) sortedList.get(copy);
currentName = current.getname();
currentID = String.valueOf(current.getid());
sortedNames[copy][0]=currentName;
sortedNames[copy][1]=currentID;
}
return sortedNames;
}
}
下面是main中调用搜索的部分:
//implement search
String searchName = "Pipps, George";
int searchID = 25;
searchList = searchGrid.nameSearch(contributorList);
if(SequentialSearch.contains(searchList, searchName)){
System.out.println(searchName + " Found.");
}
//search for contributor 25
if(SequentialSearch.contains(searchList, searchID)){
System.out.println("Contributor ID " + searchID + " found.");
}
最后一个系统。输出的是打印(ID)而不是名称。知道为什么吗?
由于您可以在调试器中运行此操作,我猜您也可以在您期望其结果为true的迭代上暂停if (name[0].equalsIgnoreCase(nameSearched))
上的程序控制。这里你可以看到name[0]和nameSearched是否有你期望的值