【问题标题】:sequential search in a string array issues字符串数组中的顺序搜索问题
【发布时间】:2014-12-11 04:39:23
【问题描述】:

Java 相对较新。我正在尝试在字符串数组中顺序搜索,但我很确定我的 if 语句有问题,因为布尔标志保持为假。该代码与 int 数组一起使用,所以我不明白这个有什么问题。

public static void sequentialNameSearch(String[] array) {
    // sequential name search
    Scanner input = new Scanner(System.in);
    String value;
    int index = 0;
    boolean flag = false;
    System.out.println("\nPlease enter a name to search for");
    value = input.next();

    while (flag == false && index < array.length - 1) {
        if (array[index] == value) {
            flag = true;
            System.out.println(array[index] + " is number "
                + (index + 1) + " in the array.");
        }
        else if (index == array.length - 1)
            System.out.println("That name is not in the array");

        index++;
    }

    input.close();
}

【问题讨论】:

标签: java arrays search sequential


【解决方案1】:

问题是你不能用 == 比较两个字符串的内容。 为此,您应该使用其中一个字符串的 equals() 或 equalsIgnoreCase() 方法。示例:

if (array[index].equals(value)) {

【讨论】:

    猜你喜欢
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多