Write an exception class named InvalidTestScore. Modify the TestScores class you
ID: 3798075 • 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
TestScores.java
public class TestScores {
double arr[];
//Parameterized constructor
public TestScores(double[] arr) {
this.arr = arr;
}
//This method will calculate the average of the test scores
public double average()
{
//Declaring variables
double avg=0.0,sum=0.0;
for(int i=0;i<arr.length;i++)
{
/* Checking whether the test score is
* in the valid range or not
*/
if(arr[i]<0 || arr[i]>100)
{
try {
throw new InvalidTestScore();
} catch (Exception e) {
System.out.println("Invalid test score.");
}
}
else
{
//calculating the sum
sum+=arr[i];
}
//Calculating the average
avg=(double)sum/arr.length;
}
return avg;
}
//Creating the Exception class
public class InvalidTestScore extends Exception {
}
}
_________________
Driver.java
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
int n;
// Scanner object is used to get the inputs entered by the user
Scanner sc = new Scanner(System.in);
//Getting the number of test scores entered by the user
System.out.print("Enter the no of Test Scores :");
n = sc.nextInt();
//Creating an array based on the size entered by the user
double testScores[] = new double[n];
/* This for loop will get the values entered
* by the user and populate those values into an array
*/
for (int i = 0; i < n; i++) {
System.out.print("Enter the Test Score" + (i + 1) + ":");
testScores[i] = sc.nextInt();
}
//Creating an Object to the TestScores class by passing the array as argument
TestScores tc = new TestScores(testScores);
//Calling the method on the TestScores class object
double avg=tc.average();
System.out.println("The Average is :"+avg);
}
}
______________________
____________________
Output#1:
Enter the no of Test Scores :5
Enter the Test Score1:66
Enter the Test Score2:77
Enter the Test Score3:-88
Enter the Test Score4:84
Enter the Test Score5:88
Invalid test score.
____________________
output#2:
Enter the no of Test Scores :5
Enter the Test Score1:61
Enter the Test Score2:88
Enter the Test Score3:65
Enter the Test Score4:92
Enter the Test Score5:89
The Average is :79.0
________________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.