簡體   English   中英

使用HashMaps的字數統計程序

[英]Word Count Program using HashMaps

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);
    }

(僅提供提示,因為這似乎是家庭作業。) my_collection是(正確地)將String鍵映射到Integer值的HashMap 在您的情況下,鍵應該是一個單詞,相應的值應該是您看到該單詞的次數(頻率)。 每次調用my_collection.get(x) ,參數x都必須是String ,即您想知道其頻率的單詞(不幸的是, HashMap並沒有強制執行此操作)。 每次調用my_collection.put(x, y)x必須是一個String ,而y需要是一個Integerint ,即該單詞的頻率。

鑒於此,請進一步考慮用作參數的內容,以及進行調用的順序以及如何操縱值。 例如,如果您已經確定my_collection不包含單詞,那么向my_collection詢問單詞的頻率是否有意義? 如果它確實包含單詞,那么在將新值放入my_collection之前,您需要如何更改頻率?

(另外,請為my_collection選擇一個更具描述性的名稱,例如frequencies 。)

嘗試這種方式-

while(data_store.hasNext()) {

                String word = data_store.next();

                   if(word.length() > 5){

                    if(my_collection.get(word)==null) my_collection.put(1);
                    else{
                       my_collection.put(my_collection.get(word)+1);
                    }

                }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM