[英]I don't get correct amount (using HashMap) in Java
I am studying programming and I have a trouble to get the correct amount of products when I try to add 3 same type products.我正在学习编程,当我尝试添加 3 个相同类型的产品时,我很难获得正确数量的产品。 For example:
例如:
basket.add("milk", 3);
basket.add("milk", 3);
basket.add("milk", 3);
System.out.println("basket price: " + basket.price() +"\n");
I get the wrong price because 'amount' doesn't increase to the value 3 since I do:我得到了错误的价格,因为“金额”没有增加到值 3,因为我这样做了:
Purchase purchase = new Purchase(product, 1, price);
I am not allowed to add additional object instances.我不允许添加额外的 object 实例。 Can you help me to fix my 'add' method to be able to have the correct amount of same type items?
你能帮我修复我的“添加”方法,以便能够拥有正确数量的同类型物品吗?
public class ShoppingBasket {
private Map<String, Purchase> basket;
public ShoppingBasket() { basket = new HashMap<String, Purchase>(); }
public void add(String product, int price) {
Purchase purchase = new Purchase(product, 1, price);
if (basket.containsKey(product)) {
purchase.increaseAmount();
basket.put(product, purchase);
} else
basket.put(product, purchase);
}
public int price() {
int price = 0;
for (Purchase item : basket.values())
price += item.price();
return price;
}
public class Purchase {
private String product;
private int amount;
private int unitPrice;
public Purchase(String product, int amount, int unitPrice) {
this.product = product;
this.amount = amount;
this.unitPrice = unitPrice;
}
public int price() {
return this.amount * this.unitPrice;
}
public void increaseAmount() {
this.amount++;
}
At most the 'amount' of the purchase will be 2, because you start with 1, increase it by 1.购买的“金额”最多为 2,因为您从 1 开始,将其增加 1。
The new amount needs to be the old amount plus 1, not 1 plus 1.新金额需要是旧金额加 1,而不是 1 加 1。
I suggest getting the existing purchase, and if it's not there, adding a new purchase for no items.我建议获取现有的购买,如果它不存在,添加一个新的购买没有项目。 Then in either case, add 1 for the new item.
然后在任何一种情况下,为新项目添加 1。 No need to keep creating a new purchase every time we want to increase the amount.
每次我们想增加金额时,都不需要继续创建新的购买。
purchase = basket.get(product);
if (purchase == null) {
purchase = new Purchase(product, 0, price);
basket.put(product, purchase);
}
purchase.increaseAmount();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.