I have a product object which is I'm using to add Product
which are adding to the cart.
Product.java
object (I have getters
and setters
),
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;
}
}
This object is belong to each item is been added to the cart. I want to find the net total of each item is being added to the cart. It is like if I have added 3 items to the cart then total of 3 subTotal
.
In my activity I tried to access the subtotal
by using,
total = Product.subTotal;
then I changed the subtotal
to static
then all the item prices change to last item added to the cart.
My problem is how can I get the total of each item added to the cart from my activity. So I can find the nettotal. Any advises will be appreciated.
I think you need some more understanding of object oriented programming. static
means, that the field (subtotal
in your case) does not belong to the Product
instance. But since subTotal
is a attribute for each instance of Product
it may not be static
so that its related to Product
. Read more on static.
To calculate the total
, you have to iterate about your Product
instance and sum all subTotals
, e.g. like this:
// 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);