首页 > 解决方案 > 如何从一个是产品,另一个是价格的 ArrayList 中获取总值?

问题描述

我正在尝试从购物车购买的所有产品中获取总价值。此信息来自 ArrayList 但我不确定我正在执行的代码是否正确。

​public class Cart {

    // creating a new list every time so need to modify..it will hold the list
    private List<CartLine> cartLineList = new ArrayList<>();

    /**
     *
     * @return the actual cartline list
     */
    public List<CartLine> getCartLineList() {
            return cartLineList;
    }

    public double getTotalValue(List<CartLine> cartLineList)
    {
         //TODO implement the method
        //return Products*Price
        double results=0;
    //  for(CartLine cartLine: getCartLineList()){
            //results += (cartLine.getQuantity()* cartLine.getProduct().getPrice());
        //}

        return results;

    }


   //more code here...

}

这就是 CartLine 的样子

公共类购物车{

private Product product;
private int quantity;

public CartLine(Product product, int quantity) {
    this.product = product;
    this.quantity = quantity;
}

public double getSubtotal() {
    return quantity * product.getPrice();
}

public Product getProduct() {
    return product;
}

public void setProduct(Product product) {
    this.product = product;
}

public int getQuantity() {
    return quantity;
}

public void setQuantity(int quantity) {
    this.quantity = quantity;
}

}

标签: javaspring

解决方案


如果getQuantity确实返回了购买的金额,并.getProduct().getPrice()返回了商品的价格,那么总和代码看起来很好(仅注释掉了)。它应该是这样的:

public double getTotalValue(List<CartLine> cartLineList) {
    double results = 0;
    for(CartLine cartLine: getCartLineList()){
        results += (cartLine.getQuantity() * cartLine.getProduct().getPrice());
    }
    return results;
}

如果您向我们展示了它是什么,那将会很有帮助CartLineCartLine在同一个实例中会不会有不同价格的不同产品?


推荐阅读