Write an exception class named InvalidTestScore. Modify the TestScores class you
ID: 3668808 • Letter: W
Question
Write an exception class named InvalidTestScore. Modify the TestScores class you wrote in Exercise 1 so that it throws an InvalidTestScore exception if any of the test scores in the array are invalid. Test your exception in a program (in a Driver class located in the same file). Your program should prompt the user to enter the number of test scores, and then ask for each test score individually. Then, it should print the average of the test scores. If the average method throws an InvalidTestScore exception, the main method should catch it and print “Invalid test score.”
Explanation / Answer
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.getMes sage());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.