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.");
}
就像标题所说,这只会产生第一个匹配,而不是数组中的所有匹配。我如何更改它以显示所有匹配项?
答案 0 :(得分:0)
删除此部分并考虑整个算法。你必须重新考虑它。
if(names[index].indexOf(searchValue) != -1)
{
found = true;
}
它只给你第一个的原因是你将found设置为true,之后Java不会进入While循环。
答案 1 :(得分:0)
不是通过将found标志设置为true来终止循环,而应该将查找结果添加到第二个数组中,该数组包含所有匹配项并继续下一次迭代直到结束。
答案 2 :(得分: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.");
}