0

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.");
 }
}
3
  • 3
    Typo: printArray(value) should be printWeightAVG(value) as well as needing to iterate over the array itself Commented Mar 4, 2014 at 1:12
  • Thanks, do you know what I do to use the array to get the average? Commented Mar 4, 2014 at 1:14
  • Think of how you'd do it on paper first Commented Mar 4, 2014 at 1:17

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0
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.");
}

2 Comments

Ahh thank you. The notes I took on arrays were very confusing. Thanks for clarifying.
Also, you don't have to cast sum to int since its already an integer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.