【问题标题】:When I print all of the values on my HashMap, printed a strange number. Why? [duplicate]当我打印 HashMap 上的所有值时,打印了一个奇怪的数字。为什么? [复制]
【发布时间】:2018-05-05 22:44:14
【问题描述】:

我正在编写一个程序,它读取一个文本文件并计算每个单词出现的次数。程序应该输出比用户给出的某个阈值更频繁使用的单词。为了避免无聊的结果,我与提供的 100 个最常用的英语单词列表进行比较。

添加到 HashMap:

try {
    // commonHashMap Filled
    Scanner sc = new Scanner(new File("commonwords.txt"));
    sc.useDelimiter("[^a-zA-Z']");
    String str;
    while (sc.hasNext()) {
        str = sc.next().toLowerCase(Locale.ENGLISH);
        commonHashMap.put(str, 1);
    }
    sc.close();


    // bookHashMap Filled
    sc = new Scanner(new File(book));
    sc.useDelimiter("[^a-zA-Z']");

    // Add the non-common words in the book to HashMap.
    while(sc.hasNext()) {
        str = sc.next().toLowerCase(Locale.ENGLISH);

        if (!commonHashMap.containsKey(str)) {

            if (bookHashMap.containsKey(str)) {
                bookHashMap.put(str, bookHashMap.get(str)+1); }
            else {
                bookHashMap.put(str, 1); }
        }
    }
    sc.close();
}

显示:

Iterator<Map.Entry<String, Integer>> iterator = bookHashSet.iterator();

while(iterator.hasNext()) {

    Map.Entry<String, Integer> x = iterator.next();

    if (iterator.hasNext()) {

        String key = x.getKey();
        int value = x.getValue();

        if (value > thresholdValue) {
            System.out.println(key + ": " + value); 
        }
    }
}

输出:

1) "The Adventures of Tom Sawyer" by Mark Twain
2) "Tale of Two Cities" by Charles Dickens
3) "The Odyssey" by Homer
Choice Book: 1
Enter Threshold Value: 200
: 27213
don't: 222
tom: 695
huck: 224
me: 212

“27213”从何而来?

【问题讨论】:

  • 尝试使用一个或多个非字母字符作为分隔符:[^a-zA-Z']+
  • What does your step debugger tell you?。使用步进调试器可以非常快速轻松地回答您的问题。在使用 StackOverflow 之前,您应该始终尝试使用步进调试器解决您的问题。

标签: java regex hashmap hashset


【解决方案1】:

我刚刚尝试了您的代码,我发现它正在计算空格。只需使用它来确保它只会计算单词:

if (str.length() != 0)

这将查看字符串长度是否为 0,这意味着它不包含任何单词。您也可以使用trim() 以获得更好的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多