Skip to content
Advertisement

How do I multiply the values in two array list, then add it to the second arraylist?

I am trying to calculate the total cost of items in the users cart. My approach to this is to store the item cost as well as the quantity in an Arraylist, and then multiply the value then add it. For example this is my Arraylist. I would like to do 2.00* 5.00 + 3.00 * 6.00 + 4.00 * 7.00 + 5.00 * 8.00. What I have done so far multiplies the first number in the first array list by every item in the second array list this is not what I am trying to do, can someone help with this.

quaninityArrayList [2.0, 3.0, 4.0, 5.0]
priceArraListy[5.0, 6.0, 7.0, 8.0]




ArrayList<Double>  priceArrayList = new ArrayList<>();
        ArrayList<Double>  quantitiyArrayList = new ArrayList<>();

        quantitiyArrayList.add(2.00);
        quantitiyArrayList.add(3.00);
        quantitiyArrayList.add(4.00);
        quantitiyArrayList.add(5.00);



        priceArrayList.add(5.00 );
        priceArrayList.add(6.00 );
        priceArrayList.add(7.00 );
        priceArrayList.add(8.00 );


        for(int i = 0; i<quantitiyArrayList.size(); i++){
          for(int j = 0; j< priceArrayList.size(); j++){
              System.out.println(quantitiyArrayList.get(i)*priceArrayList.get(j));

          }


        }

            
          

Advertisement

Answer

The following should work, however, I would strongly recommend to use a single list where each element contains the information regarding price and quantity.

float sum = 0.0;
for(int i = 0; i<quantitiyArrayList.size(); i++){
  sum += quantitiyArrayList.get(i) * priceArrayList.get(i));
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement