Stiller77 - 1 year ago 89

Java Question

I want to use the method averageCalc() which takes an array of integer numbers as its parameter and returns the average which is of double type. How can I call my method I want to return the array as a average of type double .

`public static void main(String[] args) {`

int number = 0;

number = average.int [] num ( 4, 3, 9);

System.out.println(number);

}

This is my method called averageCalc() that takes an array of integer numbers and returns the average of the numbers in the array

`public double averageCalc(int[] num) {`

int result =0;

double average = 0;

for (int i=0; i < num.length; i++) {

result = result + num[i];

}

average = (double)result / num.length;;

return average;

}

Answer Source

Form an array:

```
int[] numbers = {4, 3, 9};
```

then pass it to the method:

```
double average = averageCalc(numbers);
```

Better, declare your method as having a varargs parameter:

```
public double averageCalc(int... num) {
// same method body - num is actually int[]
}
```

Then you can call it more conveniently like this:

```
double average = averageCalc(4, 3, 9);
```