如何从ArrayList计算平均值

时间:2019-01-31 12:48:50

标签: java

我正在尝试从购物车(ArrayList)计算平均值。平均值是所有产品的总和除以数量吗?请纠正我,如果我错了,也许这就是为什么我的逻辑工作不正常的原因。

我试图做一个循环,计算所有产品的总和,然后除以其数量。

public double getAverageValue(){
    double averageValue = 0;

    for ( int i=0; i < cartLineList.size() ; i++) {
        double sum += cartLineList.get(i).getProduct();
    }

    for (CartLine cart : cartLineList) {
        averageValue = (sum / cart.getQuantity());
    }
    return averageValue;
}

public class 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;
}
}

1 个答案:

答案 0 :(得分:1)

尝试这样的事情

public double getAverageValue(){
  double averageValue = 0;
  double sum = 0;

  if(cartLineList.size() > 0){
    for ( int i=0; i < cartLineList.size() ; i++) {
      // assuming the product class has a price
      sum += cartLineList.get(i).getProduct().getPrice();
    }
    averageValue = (sum / (double)cartLineList.size())
  }

  return averageValue;
}