【问题标题】:Scanning for Character error?扫描字符错误?
【发布时间】: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


【解决方案1】:

根据Javadocs for the next() method of java.util.Scanner

public String next()

从此扫描器中查找并返回下一个完整的令牌。一个完整的标记前后是匹配分隔符模式的输入。

可以看出,这个方法没有返回Character;它返回String,这就是您收到该错误的原因。

token 基本上是位于分隔符的两个实例之间的子字符串。 Scanner 的默认分隔符是空白对象(\s\t\n 等)。因此,扫描程序会遍历文件,每次调用 next() 都会返回下一个字符序列,该序列位于被视为分隔符的字符之间。

所以您可以做的是更改分隔符,以便扫描程序将文件中的每个字符都计为一个标记,尽管这有点复杂。您可以做的是利用String 类有一个方法toCharArray() 的事实,它将字符串中的字符序列作为数组返回。您可以通过这种方式更轻松地计算单个字符:

String word = in.next().toLowerCase();
char[] charsInWord = word.toCharArray();
// ...

【讨论】:

  • 其实我正要做一个 charAt 循环,但是 toCharArray 要平滑得多。
猜你喜欢
  • 1970-01-01
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
相关资源
最近更新 更多