Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java : multiply 2 elements from an arraylist

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading