我正在尝试添加购物车商品。如果该项目存在,那么我需要通过调用方法更新项目的数量(金额)。我通过添加项目来实现它,但是当我实现需要更新现有项目的部分时,它不再起作用。请查看添加方法,并按正确的方向推动我。感谢!!!
import java.util.Set;
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.LinkedList;
public class ShoppingBasket {
private List<Purchase> basket;
public ShoppingBasket() {
basket = new LinkedList<Purchase>();
}
public void add(String product, int price) {
for (Purchase item : basket) { // cycle through the list
if (item.getProduct().equals(product)) { // item exists, update qty
item.increaseAmount();
} else { //item does not exist so add it to the list
basket.add(new Purchase(product, 1, price));
}
}
}
public int price() {
int price = 0;
for (Purchase item : basket) {
price += item.price();
}
return price;
}
public void print() {
for (Purchase item : basket) {
System.out.println(item);
}
}
}
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 String getProduct() {
return product;
}
public int price() {
// which returns the purchase price. This is obtained by raising the unit amount by the unit price
return this.amount * this.unitPrice;
}
public void increaseAmount() {
// increases by one the purchase unit amount
this.amount++;
}
public String toString() {
//returns the purchase in a string form like the following
return this.product + ": " + amount;
}
}
答案 0 :(得分:1)
我认为这可能是因为你的add方法没有考虑篮子实际上是空的情况。我可能错了,因为我在手机上并且很难测试代码,但我建议添加类似的内容:
If(basket.size()==0) basket.add(new Purchase(product, price));
编辑: 在添加我的代码之后,您现在获得的例外是因为您实际上正在修改列表并同时执行它。这是不允许的(无论是删除元素还是向列表添加元素)
然后解决方案迭代您的列表,直到找到应该添加新项目的位置或使用while循环修改金额,一旦完成,您只需使用索引添加最后或修改金额。 由于我在我的手机上,我不会使用你的变量名称,所有这些都是这样的(免责声明未经测试)
int k=0 ;
bool found=false ;
while(k<list.size() && found==false){
if(objectToAdd.equals(list.get(k)) found = true
k++
}
if(k==list.size()) list.add(objectToAdd)
else list.get(k-1).amount ++ ;