我有一個由名字組成的數組。我有一個搜索功能,搜索數組的元素,它工作正常。但是,對於數組的多個元素,我找不到如何打印返回的結果數。例如,如果找到我的例子中的「John」,那麼我不知道如何顯示找到多個結果。有人請幫助我。我需要「計數」來爲每個找到的結果增加1次。這裏是我的代碼: `在Java中查找數組中的多個搜索結果
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'來比較字符串的內容。看到http://stackoverflow.com/questions/767372/java-string-equals-versus – 2010-08-27 09:51:08