0

I'm trying to create a method called averageCustomerAge() which should return an int representing the average age of all Customer objects in the store. The issue is I'm running into an error that says I'm missing a return statement, but when I attempt to add one, I get another error saying "cannot find symbol." Anyone know how to work around this?

public int averageCustomerAge() {
    for (int i = 0; i < customerCount; i++) {
        int sum = 0;
        sum += customers[i].age;
        int average = (sum / customerCount);
    }
    return average;
}
}
Eagerissac
  • 77
  • 7
  • 1
    When you create the variable `average` in the `for`, then would that really be accessible outside of the block? Also, this isn't even how you would calculate an average. You would need to sum all values first, then divide that by `customerCount` and not in every iteration step. You can also read this regarding variable scopes: https://stackoverflow.com/questions/38177140/what-is-scope-in-java – Tom Feb 27 '19 at 12:52
  • As a side note: you probably shouldn't use int to calculate avg value, you will lose decimal part of the value. – Amongalen Feb 27 '19 at 13:31

1 Answers1

6

The average variable should be defined outside the for loop. And also, you should compute the average only once, after the sum has been computed. But, you may simplify your method to something like the following:

public int averageCustomerAge() {
    if (customerCount == 0) return 0;

    int sum = 0;
    for (int i=0; i < customerCount; i++) {
        sum += customers[i].age;
    }

    int average = sum / customerCount;

    return average;
}

Note that I return zero in the very beginning of the method should the customer count be zero. Were we not to do this, then for a zero customer count the average would be a divide by zero, which you probably don't want.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360