gpt4 book ai didi

Java 顺序搜索在匹配时不返回 true

转载 作者:行者123 更新时间:2023-11-30 08:01:07 25 4
gpt4 key购买 nike

构建我自己的顺序搜索方法,由于某种原因,我只能让 int 搜索工作,而不是 String。正在搜索的列表是根据 .csv 文件构建的,一次读取一行文件,每一行包含一个对象的所有数据。从该对象列表中提取一个二维数组,仅包含其名称和 ID,顺序搜索仅搜索这些名称和 ID。我在调试器中运行它,正在搜索的数组值确实显示了(在名称[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;
}
}

这是构建二维数组的类:

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

这是调用搜索的主部分:

 //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.");
}

最后一个 System.out 正在打印 (ID),但不打印名称。有什么想法吗?

最佳答案

由于您可以在调试器中运行它,我想您也可以在您期望的迭代中的 if (name[0].equalsIgnoreCase(nameSearched)) 上暂停程序控制结果为真。您可以在那里查看 name[0] 和 nameSearched 是否确实具有您期望的值。

关于Java 顺序搜索在匹配时不返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31907923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com