Test Scores. Write a class called TestScores. The class constructor should accep
ID: 3761611 • Letter: T
Question
Test Scores. Write a class called TestScores. The class constructor should accept an array of test scores as its argument. The class should have a member function 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 exception. There should be two classes for the exceptions; one should be called NegativeScore and other should be TooLargeScore. These exception classes will have a data member that is an integer value called score. This data member will be set in the constructor via the parameter. It should also provide a member function called getScore which returns score data member. The function in TestScores called getAverages will calculate the average (as a double) of the test scores in the array. It will also check if the score is negative or greater than 100. If it is negative it should throw an exception using the NegativeScore class. If the score is greater than 100 it should throw an excpetion using the TooLargeScore class. Main will create the instance of the TestScores class and catch the exceptions. So it needs to handle both exceptions and display the error message with the score that is invalid.
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
public class TestScores
{
private static final int MAX_SCORE = 100;
private int[] scores;
public TestScores(int[] scores)
{
this.scores = scores;
}
private int computeAverage() throws IllegalArgumentException
{
int sum = 0;
for (int i = 0; i < scores.length; i++)
{
int score = scores[i];
if (score < 0 || score > MAX_SCORE)
{
throw new IllegalArgumentException("Score (" + score + ") is not in the range 0-" + MAX_SCORE);
}
sum += scores[i];
}
int average = sum / scores.length;
return average;
}
public static void main(String[] args)
{
TestScores testScores = new TestScores(new int[] { 50, 70, 81 });
try
{
int averageScore = testScores.computeAverage();
char letterGrade;
if (averageScore < 60) letterGrade = 'F';
else if (averageScore < 70) letterGrade = 'D';
else if (averageScore < 80) letterGrade = 'C';
else if (averageScore < 90) letterGrade = 'B';
else letterGrade = 'A';
System.out.println(" Your average score is " + averageScore + " and your grade is an " +
letterGrade);
}
catch (IllegalArgumentException illegalArgumentException)
{
System.out.println(illegalArgumentException.getMessage());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.