字符串数组模拟购物车: 使用学过的技术:统计购物车中每种商品及购买的数量: String[]goods={"跑鞋","牛奶","跑鞋","泡面","果啤","牛奶","泡面","牛奶","牙刷","电脑"} 跑鞋-2 牛奶-3
时间: 2023-09-04 18:10:50 浏览: 91
模拟购物车
跑鞋-2 牛奶-3 泡面-2 果啤-1 牙刷-1 电脑-1
代码实现:
```java
public class ShoppingCart {
public static void main(String[] args) {
String[] goods = {"跑鞋", "牛奶", "跑鞋", "泡面", "果啤", "牛奶", "泡面", "牛奶", "牙刷", "电脑"};
Map<String, Integer> cart = new HashMap<>();
for (String good : goods) {
if (cart.containsKey(good)) {
cart.put(good, cart.get(good) + 1);
} else {
cart.put(good, 1);
}
}
for (Map.Entry<String, Integer> entry : cart.entrySet()) {
System.out.println(entry.getKey() + "-" + entry.getValue());
}
}
}
```
输出结果:
```
跑鞋-2
电脑-1
果啤-1
泡面-2
牙刷-1
牛奶-3
```
阅读全文