- 创建HashMap集合,以商品名做键,以售出数量做值
- 循环使用键盘输入商品名称,如果输入“end”表示结束循环不再输入数据
- 如果map中没有这个商品,售卖数量设置为1次
- 如果map中有这个商品,售卖数量加1次
- 遍历map集合,打印商品名称和售卖的数量
代码如下:
public static void main(String[] args) {
System.out.println("请输入商品名称:");
Map<String, Integer> map = getGoods(new Scanner(System.in));
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for(Map.Entry<String, Integer> entry : entrySet){
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
public static Map getGoods(Scanner sc){
Map<String, Integer> map = new HashMap<>();
String goods = null;
while(!"end".equals(goods = sc.nextLine())){
if(map.containsKey(goods)){
map.put(goods, map.get(goods) + 1);
}else {
map.put(goods, 1);
}
}
return map;
}