【发布时间】:2016-10-07 00:51:39
【问题描述】:
我正在扫描一个文件并试图跟踪一个字符出现的次数。
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 说
有下一个() 如果此扫描器的输入中有另一个令牌,则返回 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 我不完全确定。我刚刚检查了 API,实际上我什至找不到 in.next。我知道它适用于字符串......我在哪里可以找到答案?当我处理字符串时,我的扫描仪 (in) 用下一个值填充一个字符串。所以也许它不需要一个字符......
-
@TNT, "java.util.Scanner.next() 方法从这个扫描器中找到并返回下一个完整的令牌。"
-
令牌只是字符串吗?
-
它只是一个字符串
标签: java dictionary methods java.util.scanner