所以我的代码中没有错误但由于某种原因我的搜索返回真实的结果,无论数组是否包含它
public static void linSrch(String[] names) {
Scanner inputDevice = new Scanner(System. in );
System.out.println("Please enter search");
String search;
search = inputDevice.nextLine();
boolean searchReturn;
for (int index = 0; index < names.length - 1; index++) {
if (names[index] == search) {
searchReturn = true;
}
}
if (searchReturn = true) {
System.out.println(search + " is found in the array.");
} else {
System.out.println(search + " not found in the array");
}
}
答案 0 :(得分:2)
以下代码
if (searchReturn = true)
只会将searchReturn
指定为true并执行其中的代码。
您应该将其更改为
,而不是此代码if (searchReturn)
只要searchReturn
为真,就会运行
另外,要使用equals
方法而不是==
答案 1 :(得分:1)
而不是写作:
if (names[index] == search) {
searchReturn = true;
}
你必须写:
if (names[index].equals(search)) {
searchReturn = true;
}
因为,如果非原始数据类型==
检查内存地址是否相等。
也不要忘记:
if (searchReturn = true) {
System.out.println(search + " is found in the array.");
}
改变:
if (searchReturn) {
System.out.println(search + " is found in the array.");
}
因为,您要分配而不是检查。