Chapter 7 Question 8 (Average the array) (Average the array)
7.8 (Find the average of the array) Use the following method to write two overloaded methods to return the average of the array: public static int average(int[] array) public static double average(double[] array) 7.8(Average the array) Write two overloaded methods using the following method headers to return the average of the array: public static int average(int[] array) public static double average(double[] array)
Reference Code:
package chapter07;import java.util.Scanner;publicclassCode_08{
publicstaticvoidmain(String[] args){
Scanner input =newScanner(System.in);
System.out.print("Enter 10 double numbers: ");double[] array =newdouble[10];for(int i =0;i < array.length;i++)
array[i]= input.nextDouble();
System.out.print("The average is "+average(array));}publicstaticintaverage(int[] array){
int sum =0;for(int i : array)
sum += i;return sum / array.length;}publicstaticdoubleaverage(double[] array){
double sum =0;for(double i : array)
sum += i;return sum / array.length;}}
The results show that:
Enter 10double numbers:1.12.23.34.45.56.67.78.89.910.0
The average is 5.95
Process finished with exit code 0