4 回答

TA貢獻1829條經驗 獲得超7個贊
好吧,它可能有很多東西......如果你不使用ignoreCase()
. 還可以嘗試使用它來格式化您的字符串,StringTokenizer
這將使您的生活更輕松,代碼更短。

TA貢獻1827條經驗 獲得超9個贊
這里的主要問題是由以下幾行引起的:
h.get(words[i])
和
h.put(words[i].toLowerCase(), num)
您正在查找HashMap
原始大小寫中的單詞,但以小寫形式存儲它們。所以當你第一次看到“那個”時,你把它作為“那個”添加到地圖中。下次你看到“那個”時,你瞧,它不在你的地圖上!因為 Java 區分大小寫,并將“That”和“that”視為不同的字符串。因此,您將“那個”重新添加到值為 1 的地圖中。沖洗并重復您看到的每個重復的“那個”。
您可能想要做的是在開始之前將整個輸入字符串小寫。您可能還想去掉所有的標點符號,這樣句末的單詞就不會包含句號。

TA貢獻1801條經驗 獲得超16個贊
您需要像保存它一樣檢查小寫的字符串鍵。
Integer num = h.get(words[i].toLowerCase());
您還需要更改 split 方法中的正則表達式以僅獲取單詞:
String[] words = input.split("[ ,.?!:;]");

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);
}
添加回答
舉報