java - 哈希图中的字数
问题描述
我一直在为我的计算机科学课开发一个字数统计程序,我在代码中找不到错误,但它偶尔会错误地计算字数。我已经查看了以前提出的问题,但找不到答案。谁能弄清楚我做错了什么?谢谢!
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);
}
}
}
解决方案
尝试替换此行:
Integer num = h.get(words[i]);
和
Integer num = h.get(words[i].toLowerCase());
推荐阅读
- nginx - nginx-ingress 适用于 /,但不适用于子路径
- oracle - 在 Oracle 中创建组合列
- python - Python 程序在生成随机数以索引列表时挂起
- php - PHP 排序树数组
- graphviz - Graphviz如何在只绘制一层时消除层之间的边缘以及如何缩小结果的输出维度?
- ios - 检测 AVPlayerViewController 的关闭按钮的点击
- hyperledger-fabric - org1 添加资产需要组织 3 的批准(资产数据应由 ORG3 检查数据是否有效)
- php - 搜索带有部分和完整单词的正则表达式单词边界
- spring - Spring Boot 2.0 或更高版本中的 Spring Boot + Hibernate 集成(不是 spring Data JPA)
- facebook - 对于部署到heroku上的应用程序,我要为“应用程序域”插入什么