Java...
Write a class named TestScores. The class constructor should
accept an array
of test scores as its argument. The class should have a method that
returns
the average of the test scores. If any test score in the array is
negative
or greater than 100, the class should throw an
IllegalArgumentException.
Demonstrate the class in a program (create a Driver class in the
same file).
The program should ask the user to input the number of test scores
to be counted,
and then each individual test score. It should then make an array
of those scores,
create a TestScore object, and print the average of the
scores.
If an IllegalArgumentException is thrown, the main method should
catch it, print "Test scores must have a value less than 100 and
greater than 0." and terminate the program.
import java.util.Scanner; class Driver { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int totalTestScores; try { System.out.println("Enter total number of Test Scores:"); totalTestScores = sc.nextInt(); int[] testScores = new int[totalTestScores]; System.out.println("Please enter Test Scores:"); for (int i = 0; i < testScores.length; i++) { testScores[i] = sc.nextInt(); } TestScores testScoresObj = new TestScores(testScores); System.out.println("Average2 Test Score is : " + testScoresObj.averageTestScore()); } catch (IllegalArgumentException e) { System.out.println("Test scores must have a value less than 100 and greater than 0."); } } } class TestScores { private int testScores[]; public TestScores(int[] testScores) throws IllegalArgumentException { for (int i = 0; i < testScores.length; i++) { //If any of input value contain less than zero //or greater than 100 throw IllegalArgumentException if (testScores[i] < 0 || testScores[i] > 100) { throw new IllegalArgumentException(); } } //If everything went fine then assign testScores to class testScores variable this.testScores = testScores; } public double averageTestScore() { int sum = 0; double average; for (int i = 0; i < testScores.length; i++) { sum = sum + testScores[i]; } average = (double) sum / testScores.length; return average; } }
Get Answers For Free
Most questions answered within 1 hours.