java - 为什么循环没有在这里中断?
问题描述
class hashmaps{
public static void main(String args[]){
Scanner s = new Scanner(System.in);
LinkedHashMap<String,Integer> hm = new LinkedHashMap<String,Integer>();
while(true){
String a=s.next();
if(a.equals("") || a==null){
break;
}
else if(!hm.containsKey(a)){
hm.put(a,1);
}
else{
hm.put(a,hm.get(a)+1);
}
}
System.out.println(hm);
}
}
我试图从用户那里获取无限值,并在用户输入空值或字符串时尝试打印存储在哈希图中的值,但是当我在控制台中输入空值时循环没有中断。
解决方案
您需要使用nextLine();
而不是next()
等待获取非空白内容,因此当它看到换行符时它不会停止而不像nextLine
. 还
- 支票
null
没用 - 您可以使用
isEmpty
- 提高增量
merge
Scanner s = new Scanner(System.in);
LinkedHashMap<String, Integer> hm = new LinkedHashMap<>();
while (true) {
System.out.print("Give a word: ");
String a = s.nextLine();
if (a.isEmpty()) {
break;
}
hm.merge(a, 1, Integer::sum);
}
System.out.println(hm);
hm.merge(a, 1, Integer::sum);
手段_
- 钥匙
a
- 把价值
1
- 如果值已经存在,则 apply
Integer::sum
,与(prevVal, value) -> prevVal + value
推荐阅读
- coinbase-api - 使用电子邮件地址发送给另一个用户
- sql - 追加具有 LONG_RAW 数据类型的列 - SQL
- javascript - 有没有办法让渐变保留它所应用的元素的初始宽度?
- ruby-on-rails - Rails 搜索条件遵循按顺序生成的集合的顺序
- objective-c - Get method name from __objc_selrefs in dyld_shared_cache
- javascript - Puppeteer querySelectorAll 没有正确获取元素
- c++ - 在 CMake 下的多个组之间共享文件
- text - 替换大 txt 文件上的文本函数值输入不起作用
- python - python最后一个数字重复不止一次
- tabulator - 如何在制表器中通过 ajax 加载列