TreeMap 在刚刚更改的字段中返回空值

发布于 2024-12-29 08:10:58 字数 642 浏览 1 评论 0原文

我正在尝试计算 TreeMap 中单词的频率。我正在读取一个文件并将行传递给 StringTokenizer,然后将其逐字转换为字符串(当前字)。

如果 currentword = "one" 则将其放在地图上,但如果第二个单词再次为 one 而不是获取 Frequency = 1再次获取null

final StringTokenizer parser = new StringTokenizer(currentLine, " \0\t\n\r\f.,;:!?'"); 

while (parser.hasMoreTokens()) { 

        String currentWord = parser.nextToken();

        Integer frequency = frequencyMap.get(currentWord); 

        if (frequency == null) { 
            frequency = 0; 
        } 
        frequency++;
        frequencyMap.put(currentWord, frequency);
    } 

I'm trying to count the frequency of words in a TreeMap. I'm reading a file and passing the lines to a StringTokenizer and converting it afterwards to a string word by word (currentword).

If currentword = "one" then it puts it on the map, but if the second word is one again instead of fetching frequency = 1 it gets null again!

final StringTokenizer parser = new StringTokenizer(currentLine, " \0\t\n\r\f.,;:!?'"); 

while (parser.hasMoreTokens()) { 

        String currentWord = parser.nextToken();

        Integer frequency = frequencyMap.get(currentWord); 

        if (frequency == null) { 
            frequency = 0; 
        } 
        frequency++;
        frequencyMap.put(currentWord, frequency);
    } 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴我老 2025-01-05 08:10:58

看起来它对我来说工作得很好:

import java.util.*;

public class Test
{
    public static void main(String[] args) {
        Map<String, Integer> map = new TreeMap<String, Integer>();
        String[] words = { "x", "one", "y", "one" };

        for (String word : words) {
            Integer frequency = map.get(word);
            if (frequency == null) {
                frequency = 0;
            }
            frequency++;
            map.put(word, frequency);
        }

        System.out.println(map);
    }
}

输出:

{one=2, x=1, y=1}

看看你是否能想出一个类似的简短但完整的程序来演示你的问题 - 可能通过逐渐将你的“真实”代码削减为类似的东西。

Looks like it works fine to me:

import java.util.*;

public class Test
{
    public static void main(String[] args) {
        Map<String, Integer> map = new TreeMap<String, Integer>();
        String[] words = { "x", "one", "y", "one" };

        for (String word : words) {
            Integer frequency = map.get(word);
            if (frequency == null) {
                frequency = 0;
            }
            frequency++;
            map.put(word, frequency);
        }

        System.out.println(map);
    }
}

Output:

{one=2, x=1, y=1}

See if you can come up with a similar short but complete program which demonstrates your problem - possibly by gradually cutting down your "real" code to something similar.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文