Write an exception class named InvalidTestScore Modify the T

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.”

Solution

TestScores.java

import java.util.Scanner;


public class TestScores {

   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       System.out.println(\"Enter number of scores: \");
       int n = scan.nextInt();
       int a[] = new int[n];
       for(int i=0; i<n; i++){
           System.out.println(\"Enter score: \");
           a[i] = scan.nextInt();
          
       }
       try{
       double avg = average(a);
       }
       catch(InvalidTestScore exp){
       System.out.println(exp) ;
       }
   }
   public static double average(int a[]) throws InvalidTestScore{
       int sum = 0;
      
           for(int i=0; i<a.length; i++){
           if(a[i] < 0 || a[i] > 100){
               throw new InvalidTestScore(\"Invalid Test Score\");
           }
           sum = sum + a[i];  
           }
           double average = sum/(double)a.length;
           System.out.println(\"Average is \"+average);
       return average;  
   }

}

InvalidTestScore.java


public class InvalidTestScore extends Exception{
   String errorMsg ;
   public InvalidTestScore(String s){
       this.errorMsg = s;
   }
public String toString(){
return (errorMsg ) ;
}  
}

Output:

Enter number of scores:
3
Enter score:
80
Enter score:
90
Enter score:
70
Average is 80.0

Enter number of scores:
3
Enter score:
56
Enter score:
78
Enter score:
-33
Invalid Test Score

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 t
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 t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site