java - HashMap Java 的搜索键和增量值
问题描述
在我的方法中,我的目标是将字符串中的单词存储到 HashMap 中。它们的键将是一个单词,结果将是该单词出现的次数。
到目前为止,我已经尝试了搜索部分,但是,对于我增加的部分,我只打印了 yes,因为我还没有弄清楚如何做到这一点。
到目前为止,我只是希望程序在重复的次数上打印 yes,但是,我的 if 语句出现了异常。
public void countWord(){
String tokens[] = userInput.trim().replaceAll("\\s+", " ").split(" ");
for(int i = 0; i < tokens.length; ++i) {
if(bow.containsKey(tokens[i])) {
System.out.printf("yes\n");
}
else {
bow.put(tokens[i], 1);
}
}
}
我假设bow.containsKey(tokens[i]))
语法不正确,我想知道如何替换它。
解决方案
您需要在地图上检查当前令牌的计数器,如果它不存在,则创建一个值为 0 的计数器,然后递增计数器并将其放回地图中
public void countWord(){
String tokens[] = userInput.trim().replaceAll("\\s+", " ").split(" ");
for(int i = 0; i < tokens.length; ++i) {
Integer counter = bow.get(tokens[i]);
if(counter == null) {
counter = 0;
}
bow.put(tokens[i], ++counter);
}
}
如果你想改进这个语法bow.containsKey(tokens[i]))
,你可以将 tokens[i] 存储在一个变量中
public void countWord(){
String tokens[] = userInput.trim().replaceAll("\\s+", " ").split(" ");
for(int i = 0; i < tokens.length; ++i) {
String token = tokens[i];
Integer counter = bow.get(token);
if(counter == null) {
counter = 0;
}
bow.put(token, ++counter);
}
}
推荐阅读
- javascript - 如何根据是否选中单选按钮交换按钮(使用 jQuery)
- sql-server - 在 SQL SERVER 2012 中为多个项目创建单个事务
- mysql - 在连接两个表时计算没有缺失值的总销售额
- html - 如何阻止固定元素阻止滚动其后面的页面?
- java - @Mocked、@Injectable 和 @Capturing 之间有什么区别?
- c# - Unity,如何一次更新一个 UI 元素
- java - Firebase Image Load with Glide 不适用于 Android SDK 28 (Pie)
- canvas - 画布旋转时在 p5.js 画布上绘图
- php - 如何在 PostgreSQL 中查询完整的 JSON 数组?
- sqlite - 尝试在haskell中删除sqlite表时出错