-1

On now my Java program will give me list of all user input in [] these brackets. But what I want is to give me total all prices as noramally with out any brackets.

Please help me how do i do this?

public static void XalwoAmounts(ArrayList<Double> price){
for (int i = 0;  i<price.size(); i++){

    price.get(i);
    }
System.out.println("All Totals are : "+ price);

3 Answers3

2

Java 8 Stream API based solution

double sum = price.stream().mapToDouble(Double::doubleValue).sum();

You can update your method to

public static void XalwoAmounts(ArrayList<Double> price) {
        double sum = price.stream().mapToDouble(Double::doubleValue).sum();
        System.out.println("All Totals are : " + sum);
    }
Raghav
  • 4,590
  • 1
  • 22
  • 32
1

You can use a Collector, summingDouble:

double sum = price.stream().collect(Collectors.summingDouble(f -> f));
0

Right now your, loop isn't actually doing anything. Every time you loop through it, you get a value from price, but never assign it to anything. Then you directly print out price, instead of the values contained in price. Printing the ArrayList directly is the cause of the output you're getting (Eg: [12.2, 46.9]) To print out the sum of the values, try this:

    double totalPrices = 0.0;
    for (int i = 0;  i < price.size(); i++){

        totalPrices += price.get(i);
    }
    System.out.println("All Totals are: " + totalPrices);
Gulllie
  • 523
  • 6
  • 21