首页 > 解决方案 > HashMap Java 的搜索键和增量值

问题描述

在我的方法中,我的目标是将字符串中的单词存储到 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]))语法不正确,我想知道如何替换它。

标签: javahashmap

解决方案


您需要在地图上检查当前令牌的计数器,如果它不存在,则创建一个值为 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])) ,你可以将 tokens[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);
    }
}

推荐阅读