0

I am creating a method called getAveragePrice and I need it to calculate the average of values in an undefined array list (which would only be defined during the testing/implementation of said method).

    public double getAveragePrice() {
    double sum = 0;
    int x = 0; //counting variable
    do {

That is what I have right now for a start. I know that every time a value is added to the sum the count of x needs to increase by 1 so the method knows what to divide the final sum by. The only issue I have is how to set up a do loop to give me the sum of the values in an array list.

Parker Rosen
  • 43
  • 1
  • 8

6 Answers6

2

You can find the average in one line using Java 8 streams:

List<Double> vals;
// initialize vals
double avg = vals.stream().mapToDouble(Double::doubleValue).sum() / vals.size();

You can also iterate here, which is slighly more work:

double sum = 0.0;
for (double val : vals) {
    sum += val;
}

double avg = vals.size() > 0 ? sum / vals.size() : 0.0d;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I was thinking about this. What if your sum reaches Infinity because val is really large? Would your sum / vals.size() not simply be Infinity too? – AgentM Jan 26 '18 at 21:58
  • Before the sum hits infinity I think we would get some kind of overflow in the double. – Tim Biegeleisen Jan 26 '18 at 23:40
  • Regardless, it would mess up the averaging wouldn't it. I could see the only solution to be using BigDecimal and divide that. – AgentM Jan 28 '18 at 12:26
0

You should loop through each element in the list.

public double getAveragePrice() {
double sum = 0;
int x = 0; //counting variable
    do {
        sum += list.get(x);
        x++;
    } while (x < list.size());
int average = sum / x;
return average;
}

Basically, you start off the loop as x = 0, and each loop you add the value of that index, then increase x by 1. You then check if x is less than the total number of elements. If it is, then there are more elements in the list to add. If not, then you already summed all the elements. Since you added all the elements, you just need to divide it by x and then return that as the average.

MattCorr
  • 371
  • 3
  • 11
  • One other thing: You might want to check if the counting variable is zero, in the case of an empty list, to avoid a divide by zero. – Tim Biegeleisen Oct 26 '16 at 03:00
  • That's true, but I think since OP was using a do...while loop, they probably know that the list is not empty, otherwise list.get(0) would throw an error. – MattCorr Oct 26 '16 at 03:03
  • Yes, I partially assume this in my answer, it's just a nice-to-have not a must have. – Tim Biegeleisen Oct 26 '16 at 03:03
0

You can have do.while condition as:

do{
        Sum += arr[x];
        x++;
 }While(x<arr.length)

And then for avg:

Avg = sum/x
Khuzi
  • 2,792
  • 3
  • 15
  • 26
0

Alternatively you could use for(each) instead of do/while:

List<Double> values; // List<double> is no good apparently
double average = 0;
for (Double value : values) {
    average += value.doubleValue(); // I miss PHP ;)
}
average /= values.size();

This is a stylistic thing mostly, but I like to avoid explicitly using array indices to access collections (lists, arrays, whatever the language calls them) when you don't care about the order of your elements and don't intend to alter any of them.

This means you don't have a counter/pointer variable hanging around that you don't actually need later (you only care about its value during the loop) and you can't accidentally mess with your original data (the '==' to '=' typo is a classic).

Caution: I don't write much Java so perhaps foreach is frowned upon?

Edit: I don't write enough Java to use its collections correctly.

0

A Java 8 loopless solution:

myDoubleList.stream()
  .mapToDouble(Double::doubleValue)
      .average()
      .orElse(Double.NaN);
Zon
  • 18,610
  • 7
  • 91
  • 99
0

It's 21st century. No need to use any loop. Use Scala & just write

def exercise5(a: Array[Double]): Double = {
    a.sum / a.length
}
R Sun
  • 1,353
  • 14
  • 17