java - 使用 HashMap 的字数统计程序

标签 java algorithm hashmap counting

import java.io.*;
import java.util.*;

public class ListSetMap2 
{
    public static void main(String[] args)
    {
        Map<String, Integer> my_collection = new HashMap<String, Integer>();
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Enter a file name");
        String filenameString = keyboard.nextLine();
        File filename = new File(filenameString);
        int word_position = 1;
        int word_num = 1;

        try
        {
            Scanner data_store = new Scanner(filename);
            System.out.println("Opening " + filenameString);
            while(data_store.hasNext())
            {
                String word = data_store.next();
                if(word.length() > 5)
                {
                    if(my_collection.containsKey(word))
                    {
                        my_collection.get(my_collection.containsKey(word));
                        Integer p = (Integer) my_collection.get(word_num++);
                        my_collection.put(word, p);
                    }
                    else
                    {
                        Integer i = (Integer) my_collection.get(word_num);
                        my_collection.put(word, i);
                    }
                }
            }
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Nope!");
        }
    }
}

我正在尝试编写一个程序,它输入/扫描一个文件,将单词记录在 HashMap 集合中,然后计算该单词在文档中出现的次数,只计算超过 5 个字符的单词。

中间有点乱,但我遇到了如何计算该词出现的次数以及如何对每个词进行单独计数的问题。我确定这里有一个简单的解决方案,我只是想念它。请帮忙!

最佳答案

你设置词频的逻辑是错误的。这是一个适合您的简单方法:

    // if the word is already present in the hashmap
    if (my_collection.containsKey(word)) {
        // just increment the current frequency of the word
        // this overrides the existing frequency
        my_collection.put(word, my_collection.get(word) + 1);
    } else {
        // since the word is not there just put it with a frequency 1
        my_collection.put(word, 1);
    }

关于java - 使用 HashMap 的字数统计程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33244502/

相关文章:

Java:有界类型的 getClass()

java - Apache Commons FTPClient 问题 - 425 无法建立数据连接 : Connection refused

java - 使用散列搜索文件树是否更有效?

java - 仅从 map 中提取相关键

java - JavaFX 中的实时更新折线图

java - 如何在java jsf中点击按钮显示数据库中的数据

algorithm - 在设计字典之类的东西时推荐的数据结构?

将零填充到数字的Python算法

arrays - 可能更简单的 O(n) 解决方案来找到长度为 K(或更多)的具有最大平均值的子数组

java - 即使使用迭代器也会出现 ConcurrentModificationException