3

I have this code but it doesn't work!

public class Trial
{
    public static void main (String [] args)
    {
        int average;
        int m = 0;

        int [] nums = {1,6,8,9,10,60,72};

        average = getAverage(int [] nums);
    }

    public static int getAverage(int [] a)
    {
        int sum = 0;
        for(int i=0; i<a.length; i++)
            sum = sum +a[i];

        int avg = sum/a.length;
        return avg;
    }
}

Where is the problem ? I need to get the average of that array by calling a method that calculate the average.

2
  • Remove the declaration in the call, just pass "nums". Commented Jan 10, 2012 at 19:44
  • Also, consider using the expression: for (int i : a) { sum += i; } Commented Jan 10, 2012 at 19:50

4 Answers 4

8

Change your method call:

average = getAverage(nums);
Sign up to request clarification or add additional context in comments.

Comments

3

I see two problems:

  1. average = getAverage(int [] nums) should read average = getAverage(nums).
  2. The function returns an int. You might want to consider using floating-point math for the result. Otherwise you're truncating the answer to the nearest int.

5 Comments

Yeah it works! silly mistake :( Yeah, I need it to be as the nearest integer
to the nearest? so you need to make a Round or truncate or something because this line int avg = sum/a.length; may raise you an exception when you get a floating point
@Mr. No, it won't throw an exception. It'll quietly truncate.
@Mr. - The entire thing is integer math, there's no way an exception will be thrown due to 'floating point'. The only sort of exception that could be encountered is if the array is empty (divide by zero). Explicitly invoking Round() may be called for (although casting one or both operators would be necessary).
Thanks for the explanation didn't know about it, that it was called explicity, thanks!
1
average = getAverage(int [] nums); //this is wrong

average = getAverage(nums); //this is right. Just sintaxis.

Comments

0

avg can be a floating point value, but your implementation will always return integer.

Consider using floating point value for sum and avg and change return type to double.

Comments

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.