Home > Blockchain >  Java : multiply 2 elements from an arraylist
Java : multiply 2 elements from an arraylist

Time:04-28

How can I output the total cost of the products in the program? The output is always 0 with my program.

I have an arrayList and the type is an object called Product;

static ArrayList<Product> productArray = new ArrayList<Product>();

The product constructor is;

public Product(String productName, String productLink, double purchasePrice, String purchaseDate,
        String repurchaseDate, int quantity) {
    this.productName = productName;
    this.productLink = productLink;
    this.purchasePrice = purchasePrice;
    this.purchaseDate = purchaseDate;
    this.repurchaseDate = repurchaseDate;
}

I'm trying to loop through the arraylist, to out put the total cost of the products. The total cost of the products is the quantity*thePurchasePrice. The method is;

public static void totalSpend() {
    
    double productCost = 0, totalCost = 0;

    for (int i = 0; i < productArray.size(); i  ) {
        
        productCost = ((double)productArray.get(i).getQuantity()) * ((double)productArray.get(i).getPurchasePrice());
        
        System.out.println("\nThe " productArray.get(i).getProductName() " costs £" productArray.get(i).getPurchasePrice());
        
        totalCost = productCost;
        
    }
    
    System.out.println("\nThe total cost is £" totalCost);

}//methodEnd

I've tried casting productCost to a double and int, tried moving the productCost and totalCost to within the loop.

CodePudding user response:

In the future, you should post more of the code to see how it ties together, but based on what you have here, I think I see the problem. The constructor for Product has a parameter for quantity, but you don't actually save that value anywhere in the constructor.( this.quantity = quantity ) Assuming that the getQuantity() returns an int stored somewhere in the Product class, it will likely just be returning the default int value of zero, resulting in the product cost always being zero no matter what else you do.

CodePudding user response:

How do you pass an array to a method? It looks like your method is working with an array without data. Initialize the array with Product objects and pass it to the method

Try: public static void totalSpend(ArrayList<Product> productArray){

  • Related