首页 > 解决方案 > 为什么循环没有在这里中断?

问题描述

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);
}
}

我试图从用户那里获取无限值,并在用户输入空值或字符串时尝试打印存储在哈希图中的值,但是当我在控制台中输入空值时循环没有中断。

标签: javaloopshashmap

解决方案


您需要使用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

推荐阅读