user412308 user412308 - 22 days ago 5
Java Question

Java - Error in finding the average of an array

my code is here

/* The problem is to print 100 random numbers, get the average of those numbers, and then find the number of items
greater than the average. */

import java.util.*;
public class Test {
public static void main(String[] args) {
System.out.println("This program prints 100 numbers, gets the average of those numbers, and then finds the " +
"numbers of items greater than the average.");
int myArray[] = new int[100];
System.out.println("The values are: ");
for (int i = 0; i < myArray.length; i++) {
myArray[i] = (int) (Math.random() * 100 + 1);
System.out.println(myArray[i] + " ");
}
System.out.println("The average is ");
getAverage(myArray);
}

public static void getAverage(int array[]) {
double average = 0;
for (int i = 0; i < array.length; i++) {
double sum = 0;
sum += array[i];
average = sum / array.length;
}
System.out.println(average);
}
}


I should print 100 random numbers, get the average of those and display it. Also I should find the number of items greater than the average. I think there is a logic error somewhere in the code, since the output is usually a 0.4 or 0.6 number. Any would be appreciated. Thanks!

Answer

Inside of your for-loop in getAverage, you are resetting the sum to 0 on every iteration. You should also take the average at the end of the looping.

Try this instead:

public static void getAverage(int array[]) {
    double average = 0;
    double sum = 0;
    for (int i = 0; i < array.length; i++) {
        sum += array[i];
    }
    average = sum / array.length;
    System.out.println(average);
}