【问题标题】:Search Keys and Increment Value for HashMap Java [duplicate]HashMap Java的搜索键和增量值[重复]
【发布时间】:2018-10-27 23:47:52
【问题描述】:

在我的方法中,我的目标是将字符串中的单词存储到 HashMap 中。它们的键将是一个单词,结果将是该单词出现的次数。

到目前为止,我已经尝试了搜索部分,但是,对于我增加的部分,我将其保留为仅打印 yes,因为我也没有弄清楚如何做到这一点。

到目前为止,我只是希望程序在重复的次数内打印 yes,但是,我的 if 语句出现异常。

public void countWord(){

    String tokens[] = userInput.trim().replaceAll("\\s+", " ").split(" ");

    for(int i = 0; i < tokens.length; ++i) {
        if(bow.containsKey(tokens[i])) {
            System.out.printf("yes\n");
        }
        else {
            bow.put(tokens[i], 1);
        }
    }
}

我假设bow.containsKey(tokens[i])) 的语法不正确,我想知道如何替换它。

【问题讨论】:

  • 究竟是什么错误或异常(编辑问题以将其显示为格式正确的文本)?
  • java.lang.NullPointerException

标签: java hashmap


【解决方案1】:

您需要在地图上检查当前令牌的计数器,如果不存在,则创建一个值为 0 的计数器,然后递增计数器并将其放回地图中

public void countWord(){

    String tokens[] = userInput.trim().replaceAll("\\s+", " ").split(" ");

    for(int i = 0; i < tokens.length; ++i) {
        Integer counter = bow.get(tokens[i]);
        if(counter == null) {
            counter = 0;
        }
        bow.put(tokens[i], ++counter);
    }
}

如果你想改进这个语法bow.containsKey(tokens[i])) 您可以将标记[i] 存储在变量中

public void countWord(){

    String tokens[] = userInput.trim().replaceAll("\\s+", " ").split(" ");

    for(int i = 0; i < tokens.length; ++i) {
        String token = tokens[i];
        Integer counter = bow.get(token);
        if(counter == null) {
            counter = 0;
        }
        bow.put(token, ++counter);
    }
}

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 2013-02-26
    • 2011-10-30
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2016-03-31
    • 2010-09-29
    • 2021-10-15
    相关资源
    最近更新 更多