Search code examples
javafor-loopreturn

Missing return statement in for loop - return int representing the average age of all Customer objects in the store


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;
}
}

Solution

  • 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.