In class, we wrote a class that used arrays. We are going to take the methods readArray(), calcAverage() and writeArray() and turn them into a separate class.
Write a class called TestArray that contains main.
For extra credit, include the array and its actual size in the class. Below you will find the class ArrayAverage:
import java.util.Scanner;
public class AverageArray {
// Read in an array and calculate and print its average
public static void main(String[] args) {
int [] myArray = new int[9];
readArray(myArray);
double average = calcAverage(myArray);
System.out.printf("The average is %4.1f\n", average);
writeArray(myArray);
}
// readArray() - Read in the array
public static void readArray(int[] x) {
Scanner keyb = new Scanner(System.in);
int index;
for (index = 0; index < 9; index++) {
System.out.println("Enter x[" + index + "]");
x[index] = keyb.nextInt();
}
}
// calcAverage() - Calculate and return the average
// of an array
public static double calcAverage(int[] x) {
int index;
double sum = 0.0;
for (index = 0; index < 9; index++)
sum = sum + x[index];
return sum / 9;
}
// writeArray() - Print the array
public static void writeArray(int[] x) {
int index;
for (index = 0; index < 9; index++)
System.out.println("x[" + index + "] = " + x[index]);
}
}