0
    String searchValue;     
    boolean found = false;
    int index = 0;

    System.out.println("Enter a name to search for in the array.");
    searchValue = kb.nextLine();

    while (found == false && index < names.length) {
        if (names[index].indexOf(searchValue) != -1) {
            found = true;
        } else {
            index++;
        }
    }
    if (found) {
        System.out.println("That name matches the following element:");
        System.out.println(names[index]);
    } else {
        System.out.println("That name was not found in the array.");
    }

就像标题所说的那样,这只会产生第一个匹配项,而不是数组中的所有匹配项。我将如何更改它以显示所有匹配项?

4

3 回答 3

0

与其通过将 found 标志设置为 true 来终止循环,不如将结果添加到第二个数组中,该数组包含所有匹配项并继续下一次迭代,直到结束。

于 2013-11-14T19:58:46.590 回答
0

找到第一个匹配项后,您将退出循环 - 这个怎么样:

    while (index < names.length) {
        if (names[index].indexOf(searchValue) != -1) {
            System.out.println("That name matches the following element:");
            System.out.println(names[index]);
            found = true;
        } else {
            index++;
        }
    }

    if (!found) {
        System.out.println("That name was not found in the array.");
    }
于 2013-11-14T20:00:52.800 回答
0

删除这部分并总体考虑整个算法。你必须重新考虑它。

if(names[index].indexOf(searchValue) != -1)
{
    found = true;
}

它只给你第一个的原因是你将 found 设置为 true 并且 Java 不会在那之后进入 While 循环。

于 2013-11-14T19:57:38.053 回答