字符串数组的线性搜索

Linear Search of string array

所以我的代码没有错误,但出于某种原因,无论数组是否包含它,我的搜索都会返回真实结果

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

以下代码

if (searchReturn = true) 

只会将 searchReturn 赋值为 true 并执行其中的代码。

您应该将此代码改为

if (searchReturn)

searchReturn 为真时 运行

还要比较字符串使用 equals 方法而不是 ==

而不是写作:

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

因为,你是在赋值而不是检查。