I am trying to calculate the average value from a shopping cart (ArrayList). Average value means the sum all the products divided by its quantity?, correct me If I am wrong please maybe that's why my logic is not working well.
I was trying to do a loop for calculating the sum of all the products and then divided by its quantity.
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;
}
}
try something like this
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.