简体   繁体   中英

How to find the average of double values in an array list using a do loop?

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.

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;

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.

You can have do.while condition as:

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

And then for avg:

Avg = sum/x

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.

A Java 8 loopless solution:

myDoubleList.stream()
  .mapToDouble(Double::doubleValue)
      .average()
      .orElse(Double.NaN);

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

def exercise5(a: Array[Double]): Double = {
    a.sum / a.length
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM