我正在扫描一个文件并试图追踪一个角色出现的次数。扫描字符错误?
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