我的家庭工作任务有问题。我可以处理语法,但不能处理逻辑。你能给我一些提示吗?
我想要实现的是add方法会通过使用increaseAmount方法增加产品数量。现在,每次调用方法时,它都会将amount的值重置为“1”。使这种复杂化的原因是我不允许使用任何其他私有变量。
private Map<String, Purchase> shoppingCart = new HashMap<String, Purchase>();
public void add (String product, int price) {
Purchase purchase = new Purchase (product, 1, price);
//the line abowe returns the value back to 1 which I don't want.
if(shoppingCart.containsKey(product)) {
shoppingCart.put(product, purchase);
purchase.increaseAmount();
}
else {
shoppingCart.put(product, purchase);
产品构造函数:
public Ostos(String product, int amount, int price) {
increaseAmount方法的代码:
private int amount;
public void increaseAmount() {
this.amount = (this.amount + 1);
答案 0 :(得分:6)
不要在开始时创建新的购买,只有在它尚未存在的情况下创建它
public void add (String product, int price) {
if(shoppingCart.containsKey(product)) {
Purchase purchase = shoppingCart.get(product);
purchase.increaseAmount();
//You might have to put the purchase back into the cart I'm not sure
}
else {
Purchase purchase = new Purchase (product, 1, price);
shoppingCart.put(product, purchase);
}
答案 1 :(得分:1)
您必须从shoppingCart
检索值,然后增加金额。您永远不会致电shoppingCart.get
,因此您每次都会盲目地put
将新的购买对象添加到地图中来替换该值。