【问题标题】:Linear Search of string array [duplicate]字符串数组的线性搜索[重复]
【发布时间】:2015-11-16 00:06:41
【问题描述】:

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

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

【问题讨论】:

  • 要比较两个字符串是否相等,请使用names[index].equals(search) 而不是使用==
  • 另外,if (searchReturn = true) { 不检查是searchReturntrue。它分配true 给变量searchReturn。你想要的只是if (searchReturn) { ...

标签: java arrays string linear-search


【解决方案1】:

以下代码

if (searchReturn = true) 

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

你应该把它改为

if (searchReturn)

只要searchReturn 为真,就会运行

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

【讨论】:

  • 或者只是if (searchReturn),它更干净。
【解决方案2】:

而不是写:

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

因为,您是在分配而不是检查。

【讨论】:

  • 谢谢,让我走上正轨,我最终对其进行了改造,并使用了startsWith、endWith和contains来满足我的需要,但这引导我朝着我需要的方向前进!非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 2012-03-07
相关资源
最近更新 更多