亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java中的字數統計類不計算出現的每一個“那個”

Java中的字數統計類不計算出現的每一個“那個”

滄海一幻覺 2022-06-23 19:32:33
我正在嘗試在 Java 中創建一個 hashmap 類來計算出現的每個單詞。它在大多數情況下都有效,但是當我嘗試使用該段落時:“他們給嬰兒取名為蘇珊。那個經理發現盒子是空的。唐娜的女兒把門開著。那個音樂家覺得這本書很有趣。那個牙醫給狗起名叫菲多”它檢測除“那個”之外的所有其他單詞的正確數量。“那個”在段落中出現了 3 次,但它只檢測到一個“那個”。這是代碼:import java.util.*;public class WordCounts extends ConsoleProgram{    public void run()    {        HashMap<String,Integer> h = new HashMap<String,Integer>();        String input = readLine("Enter a string: ");        String[] words = input.split(" ");        for(int i=0; i<words.length; i++)        {            Integer num = h.get(words[i]);            if( num == null)                num = new Integer(1);            else                num = new Integer(num.intValue() + 1);            h.put(words[i].toLowerCase(), num);        }        printSortedHashMap(h);    }    /*     * This method takes a HashMap of word counts and prints out     * each word and it's associated count in alphabetical order.     *     * @param wordCount The HashMap mapping words to each word's frequency count     */    private void printSortedHashMap(HashMap<String, Integer> wordCount)    {        // Sort all the keys (words) in the HashMap        Object[] keys = wordCount.keySet().toArray();        Arrays.sort(keys);        // Print out each word and it's associated count        for (Object word : keys)         {            int val = wordCount.get(word);            System.out.println(word + ": " + val);        }    }}如果有人可以提供幫助,我將不勝感激。提前致謝。編輯:我在描述中不小心寫了“那個”而不是“那個”;我的意思是我試圖弄清楚為什么班級不計算每個“那個”。
查看完整描述

4 回答

?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

好吧,它可能有很多東西......如果你不使用ignoreCase(). 還可以嘗試使用它來格式化您的字符串,StringTokenizer這將使您的生活更輕松,代碼更短。



查看完整回答
反對 回復 2022-06-23
?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

這里的主要問題是由以下幾行引起的:

h.get(words[i])

 h.put(words[i].toLowerCase(), num)

您正在查找HashMap原始大小寫中的單詞,但以小寫形式存儲它們。所以當你第一次看到“那個”時,你把它作為“那個”添加到地圖中。下次你看到“那個”時,你瞧,它不在你的地圖上!因為 Java 區分大小寫,并將“That”和“that”視為不同的字符串。因此,您將“那個”重新添加到值為 1 的地圖中。沖洗并重復您看到的每個重復的“那個”。

您可能想要做的是在開始之前將整個輸入字符串小寫。您可能還想去掉所有的標點符號,這樣句末的單詞就不會包含句號。


查看完整回答
反對 回復 2022-06-23
?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

您需要像保存它一樣檢查小寫的字符串鍵。

Integer num = h.get(words[i].toLowerCase());

您還需要更改 split 方法中的正則表達式以僅獲取單詞:

String[] words = input.split("[ ,.?!:;]");


查看完整回答
反對 回復 2022-06-23
?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

簽出代碼的內聯注釋,以更新字符串數組中的字數。


 for(int i=0; i<words.length; i++)

    {


// in the below line, while you are adding it to the map, the string was not converted to lowercase

        Integer num = h.get(***words[i].toLowerCase()***);

        if( num == null)

            num = new Integer(1);

        else

            num = new Integer(num.intValue() + 1);


// here you were doing it..

        h.put(words[i].toLowerCase(), num);

    }


查看完整回答
反對 回復 2022-06-23
  • 4 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號