java - 如何从一个是产品,另一个是价格的 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;
}
}
解决方案
如果getQuantity
确实返回了购买的金额,并.getProduct().getPrice()
返回了商品的价格,那么总和代码看起来很好(仅注释掉了)。它应该是这样的:
public double getTotalValue(List<CartLine> cartLineList) {
double results = 0;
for(CartLine cartLine: getCartLineList()){
results += (cartLine.getQuantity() * cartLine.getProduct().getPrice());
}
return results;
}
如果您向我们展示了它是什么,那将会很有帮助CartLine
。CartLine
在同一个实例中会不会有不同价格的不同产品?
推荐阅读
- google-chrome - html5视频在谷歌浏览器上首次加载时无法搜索视频,但刷新页面几次后,它可以搜索
- java - 按值分组并分离输出
- php - 使用 JOIN 更新 MySQL 中的两个表
- c++ - 无法理解声明中的 const 结构
- android - 通过杰克逊解析具有多个元素的xml文件
- servicestack - 当我使用 ServiceStack.OrmLite.SqlServer Db.Select
有时 Result 是 TableB 的行或 TableA 的其他行 - html - Bootstrap 4 - 部分下一张幻灯片上的光滑滑块渐变效果
- java - 将 JSON 转换为对象抛出 JsonMappingException “无法反序列化类实例出 START_ARRAY 令牌”
- docker - ForgeRock 产品(即 AM、IDM、DS 和 IG)在 Docker 容器中使用的最佳操作系统是哪个?
- css - 我在 hompage 上的字体工作正常,但在其他页面上却没有