Please write this Java program as simple as possible and with comments throughou
ID: 3730198 • Letter: P
Question
Please write this Java program as simple as possible and with comments throughout explaining what is happening. Thank you!
Exercise 2: Design and implement a Java program for programming exercise 7.8, page 277 (name it AverageArray), to compute and display the average of values in an array. Follow the instructions in the problem statement (but change the return value type of the method which takes an array of int values as the parameter to double). Note that you need to write two overloaded methods as specified and design these methods to accurately compute the average of an array with any number of elements. Design the main method of your program to handle all input and output and to allow the user to re-run the program with different sets of inputs. Document your code and organize the output using appropriate formatting techniques.
Explanation / Answer
/**The java program that prompts user to enter
* 10 double values and calls the overloaded average method
* and print the average on console.*/
//TestAverageArray.java
import java.util.Scanner;
public class TestAverageArray
{
public static void main(String[] args)
{
Scanner kb=new Scanner(System.in);
final int size=10;
double[] dvalues=new double[size];
//read 10 double values
for (int i = 0; i < dvalues.length; i++)
{
System.out.printf("Enter value %d:",i+1);
//read double value as string and parse to double
dvalues[i]=Double.parseDouble(kb.nextLine());
}
/**Since average is an overaloded mehtod that takes double and integer
* array, the average takes double as since double array is declared in
* main method .
* If integer array is declared and read values into integer array
* , then the average method is applied on
* integers .*/
System.out.printf("Average : %4.2f ",AverageArray.average(dvalues));
}
}
--------------------------------------------------------------------------------------------------------------------------------------------
//AverageArray.java
public class AverageArray
{
/**The method average that takes integer
* array as input and returns the average
* of array elements*/
public static int average(int[] array)
{
int sum=0;
for (int i = 0; i < array.length; i++)
{
sum+=array[i];
}
return sum/array.length;
}
/**The method average that takes double
* array as input and returns the average
* of array elements*/
public static double average(double[] array)
{
double sum=0;
for (int i = 0; i < array.length; i++)
{
sum+=array[i];
}
return sum/array.length;
}
}//end of the class AverageArray
--------------------------------------------------------------------------------------------------------------------------------------------
Sample Output :
Enter value 1:5
Enter value 2:6
Enter value 3:5.5
Enter value 4:6
Enter value 5:3
Enter value 6:5
Enter value 7:4
Enter value 8:8
Enter value 9:9
Enter value 10:10
Average : 6.15