我正在掃描一個文件並試圖追蹤一個角色出現的次數。掃描字符錯誤?
public static Map<Character, Integer> getCountMap(Scanner in){
Map<Character, Integer> wordCountMap = new TreeMap<Character, Integer>();
while (in.hasNext()){
Character word = in.next().toLowerCase();
//CHAR HAS BEEN SEEN, ADD
if(wordCountMap.containsKey(word)){
int count = wordCountMap.get(word);
wordCountMap.put(word, count + 1);
}
//NEW CHAR, CREATE
else {
wordCountMap.put(word, 1);
}
}
return wordCountMap;
}
我得到一個錯誤Character word = in.next().toLowerCase();
我檢查的Java API,和人物肯定是要toLowerCase()
訪問。然而,掃描儀的API說
hasNext() 如果此掃描程序在其輸入中有另一個標記,則返回true。
這是否意味着掃描儀無法掃描每個字符? 不應該只是掃描角色,將它們添加到地圖,並增加每次看到的東西的計數?
最後說明:如果每個Character
替換爲String
,此代碼運行得很好。我可以得到一個字數沒有問題。字符數,而不是太多。
主要方法(在這種情況下是必需的)
public static void main(Character[] args) throws FileNotFoundException{
//read the book into the map
Scanner in = new Scanner(new File("moby.txt"));
Map<Character, Integer> wordCountMap = getCountMap(in);
for (Character word: wordCountMap.keySet()){
int count = wordCountMap.get(word);
if (count > OCCURRENCES){
System.out.println(word + " occurs " + count + " times.");
}
}
}
你確定'in.next()。toLowerCase()'返回一個'Character'對象嗎? – TNT
@TNT我不完全確定。我剛剛檢查了API,實際上甚至找不到in.next。我知道它適用於字符串......我在哪裏可以弄清楚這一點? 當我處理字符串時,我的掃描器(in)用下一個值填充字符串。所以也許它不需要字符... – Podo
@TNT, 「The java.util.Scanner.next()方法查找並返回來自此掃描器的下一個完整標記。」 – Podo