【发布时间】:2010-08-26 19:54:20
【问题描述】:
我有一个由名字组成的数组。我有一个搜索功能,可以搜索数组的元素,它工作正常。但是,对于数组的多个元素,我不知道如何打印返回了多少结果。例如,如果在我的示例中找到“John”,我不知道如何表明找到了多个结果。有人请帮助我。对于找到的每个结果,我需要获得“计数”以增加 1 倍。这是我的代码: `
import java.util.*;
class Search {
public static void main(String[] args) {
Scanner search = new Scanner(System.in);
String[] firstName = new String[]{"John", "Thomas", "Samuel", "Chris", "Daniel", "Joey", "David", "Joshua", "Michael", "John"};
Arrays.sort(firstName);
System.out.print("Enter a search term: ");
String name = search.next();
int i;
boolean foundIt = false;
search:
for (i = 0; i < firstName.length; i++) {
if (firstName[i] == name) {
foundIt = true;
}
}
if (foundIt = true){
System.out.println("Your search term of " + name + " produced " + count + " search results");
}
else {
System.out.println("Your search term of " + name + " did not return any results");
}
}
}
【问题讨论】:
-
不要使用
==来比较Java 中的字符串!这只会在两个字符串是同一个实例时返回 true,使用equals比较字符串的内容。见stackoverflow.com/questions/767372/java-string-equals-versus