In: Computer Science
Write a complete Java code that contain two classes. A GradeBook and a GradeBookTester.
- The GradeBook class contains the followings:
- An array of grades (integer array) declared as a field.
- A constructor that takes an integer value as parameter (len), and creates the grades array of size equals to len.
- A method called fillArray that fills the grades array with random integers. Acceptable values are between 1 and 100 (inclusive)
- A method called printStatistics that prints 4 values: the average of the grades, the minimum grade, the maximum grade, and the median grade (the middle value of the sorted array).
- The GradeBookTester contains the main and do the followings:
- Uses the input dialog to ask the user to enter an integer value (assume that the user will enter a value that is non-zero and positive / no need to check)
- creates an object of GradeBook class while passing the entered value as parameter.
- calls the functions fillArray and printStatistics for testing.
Please Solve As soon as
Solve quickly I get you thumbs up directly
Thank's
GradeBook.java
import java.util.Random;
public class GradeBook {
private int grades[];
public GradeBook(int size) {
grades = new int[size];
}
// method to fill the array
public void fillArray() {
Random rn=new Random();
// loop through the array and randomly fill it
for (int i = 0; i < grades.length; i++) {
grades[i] = rn.nextInt(100) + 1;
}
}
// print the statistics of the array values
public void printStatistics() {
int max = grades[0], min = grades[0];
float avg=0, median=0;
// loop through the array
for (int a : grades) {
if (a < min)
min = a;
if (a > max)
max = a;
avg += a;
}
avg = avg / grades.length;
// sort the array
for (int i = 0; i < grades.length - 1; i++) {
for (int j = 0; j < grades.length - i - 1; j++) {
if (grades[j] > grades[j + 1]) {
int t = grades[j];
grades[j] = grades[j + 1];
grades[j + 1] = t;
}
}
}
int l = grades.length;
median = l % 2 == 0 ? (grades[l / 2] + grades[l / 2 + 1]) / 2 : grades[l / 2];
System.out.println("Minimum : " + min + "\nMaximum : " + max + "\nAverage : " + avg + "\n Median : " + median);
}
}
Screenshot
GradeBookTester.java
import java.util.*;
public class GradeBookTester {
public static void main(String args[]) {
Scanner x = new Scanner(System.in);
// get user input
System.out.print("Enter size of grades array : ");
int l = Integer.parseInt(x.nextLine());
// call GradeBook methods
GradeBook grade = new GradeBook(l);
grade.fillArray();
grade.printStatistics();
}
}
SCreenshot
Output