user11124425
user11124425

Reputation: 971

Manipulate the method sum() in the method average()

I have an array below:

int[] tab = {10,4,23,45,28,34,89,9,16,55};

My method sum() works correctly:

public static int sum(int[] array){
      int sum_array = 0;
      for(int i=0;i<array.length;i++){
        sum_array += array[i];
      }
      return sum_array;
    }

Now, I would like to create a method average() by adding the method sum().

I have this for now:

public static float average(int[] tab){
      return sum[tab] / length[tab];
}

My error message is:

Main.java:97: error: cannot find symbol
      return sum[tab] / length[tab];

I don't understand the problem.

Thank you in advance for your help.

Upvotes: 1

Views: 34

Answers (1)

Eran
Eran

Reputation: 393851

Both sum[tab] and length[tab] are invalid, since sum and length are not arrays.

It should be:

public static float average(int[] tab){
    return sum(tab) / tab.length;
}

Note that this will return a whole number (int) cast to float, since you are dividing two ints.

If you wish the result to be more accurate (i.e. including fractions), you should perform floating point division, by casting one of the operands to float:

public static float average(int[] tab){
      return (float) sum(tab) / tab.length;
}

Upvotes: 3

Related Questions