Question

I need to calculate the average value of the array and print it out. What am I doing wrong here?

public class Weight {
public static void main(String[] args) {
    int[] value = {98, 99, 98, 100, 101, 102, 100, 104, 105,
                    105, 106, 105, 103, 104, 103, 105, 106, 107, 106,
                    105, 105, 104, 103, 102, 102, 101, 100, 102};
    printArray(value);
}

public static void printWeightAVG(int[] value) {
    double average = ((int)value / 28.0);
    System.out.println("The average weight is " + average + " lbs.");
 }
}
Was it helpful?

Solution 3

public static void printWeightAVG(int[] value) {

    int sum =0;
    for(int count=0; count<value.length; count++) {
       sum = sum + value[count];
    }
    //double average = ((int)sum/ 28.0); (as in your code)
    double average = sum/value.length; //(better way)
    System.out.println("The average weight is " + average + " lbs.");
}

OTHER TIPS

an array is not a single value, it is a collection of values. You need to iterate through it with a for loop

int sum = 0;
for(int i=0; i<value.length; i++) {
  sum += value[i];
}
System.out.println("average is "+sum/value.length);

Basically, what this is saying is "go through every index of the array, then add the value at that index of the array to the sum variable". if the array is: [1,4,3] then value[1] will be 4. If you iterate over every value with a variable, you can individually reference everything contained within the array.

You're trying to divide an Array by a number. You need to divide the sum of the numbers in value by 28, or however many numbers there are, to get the average.

A few notes:

1) rather than hardcoding the number of elements, you can get it by using .length. So if sum is the sum of all of the elements in value, you can say average =sum/ value.length.

2) Be careful with types. Dividing an int by a float or a double will result in a non-int value (which in most cases is what you want, but you need to be careful, particularly if precision is required)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top