你好再次堆栈溢出.. ers,我创建了这段代码来顺序搜索数组以找到一个值,在这种情况下是一个名称。但是我不能让它工作,它不会找到我输入的名字,并且总是返回一个值-1。
当我将所有类型更改为 INT 并在年龄数组上进行搜索时,它起作用了,所以它可能与字符串类型有关?有人可以帮帮我吗?
公共静态无效主要(字符串[]参数){
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;
}