你好再次堆栈溢出..呃, 我创建了这段代码来顺序搜索数组以查找值,在本例中是名称。但是我无法让它工作,它找不到我输入的名称,并且始终返回值 -1。
当我将所有类型更改为 INT 并对年龄数组进行搜索时,它起作用了,所以它可能与字符串类型有关?有人可以帮我吗?
public static void main(String[] args) {
String[] name = {"John", "bert", "Elle", "beth"};
String[] sex = {"Male", "Male", "female", "female"};
int[] age = {18, 25, 22, 36};
int found;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name to search: ");
String searchName = keyboard.next();
found = searchNames(name, searchName);
if(found == -1)
System.out.println("Error, not found: " + found);
else
System.out.println("Found At: " + found);
}
private static int searchNames(String[] name, String searchName) {
int i = 0, foundAt = -1;
boolean found = false;
while (!found && i < name.length)
{
if (name[i] == searchName)
{
found = true;
foundAt = i;
}
i++;
}
return foundAt;
}
最佳答案
此功能很快就会关闭,但请使用 .equals()
来比较字符串。
关于java - Java 中的顺序字符串搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15938943/