使用 android 中的对象 class 计算 nettotal

Calculation of nettotal using Object class in android

我有一个产品对象,我用它来添加 Product,它正在添加到购物车。

Product.java对象(我有getterssetters),

public class Product {

    public double price;
    public String description;
    public int quantity;
    public String instructions;
    public double subTotal;

    public Product(String description, int quantity, String instructions,
            double subTotal, double price) {

        this.price = price;
        this.description = description;
        this.quantity = quantity;
        this.instructions = instructions;
        this.subTotal = subTotal;
    }
}

此对象属于已添加到购物车的每个项目。我想找到添加到购物车中的每件商品的净总额。这就像如果我在购物车中添加了 3 件商品,那么总共有 3 件 subTotal

在我的 activity 中,我尝试使用

访问 subtotal
total = Product.subTotal;

然后我将 subtotal 更改为 static 然后所有商品的价格都更改为最后添加到购物车的商品。

我的问题是如何从 activity 中获取添加到购物车的每件商品的总数。所以我可以找到 nettotal。任何建议将不胜感激。

我认为您需要对面向对象编程有更多的了解。 static 表示该字段(在您的情况下为 subtotal)不属于 Product 实例。但是由于 subTotalProduct 的每个实例的属性,它可能不是 static,因此它与 Product 相关。 Read more on static.

要计算 total,您必须迭代 Product 实例并对所有 subTotals 求和,例如像这样:

// empty List
List<Product> myProducts = new ArrayList<Product>();
myProducts.add(new Product("description",1, "instructions", 5, 7));
[...]
double total = 0;
for(Product product : myProducts) {
   total += product.subTotal * product.quantity;
}
System.out.println("Total: " + total);

让您购物 ArrayList 件商品。

产品会有方法

  public double getsubtotal()
    {
       return price*quantity;
    }

total 将遍历购物车

for(Product prod:cart)
{
   total = total + prod.getsubtotal
}