我的程序讀取一個文本文件並列出文件中每個詞的頻率。接下來我需要做的是讀取文件時忽略某些詞,如'the','an'。我已經創建了這些單詞的列表,但不知道如何在while循環中實現它。謝謝。讀取文件時忽略某些詞
public static String [] ConnectingWords = {"and", "it", "you"};
public static void readWordFile(LinkedHashMap<String, Integer> wordcount) {
// FileReader fileReader = null;
Scanner wordFile;
String word; // A word read from the file
Integer count; // The number of occurrences of the word
// LinkedHashMap <String, Integer> wordcount = new LinkedHashMap<String, Integer>();
try {
wordFile = new Scanner(new FileReader("/Applications/text.txt"));
wordFile.useDelimiter(" ");
} catch (FileNotFoundException e) {
System.err.println(e);
return;
}
while (wordFile.hasNext()) {
word = wordFile.next();
word = word.toLowerCase();
if (word.contains("the")) {
count = getCount(word, wordcount) + 0;
wordcount.put(word, count);
}
// Get the current count of this word, add one, and then store the
// new count:
count = getCount(word, wordcount) + 1;
wordcount.put(word, count);
}
}
getCount()方法裏面有什麼?它只是'wordcount.get(word)'?您使用的是哪個版本的Java?另外考慮關閉'掃描儀',否則你會有資源泄漏。 –
你使用Java 8嗎? – fge