Write a class named TestScores The class constructor should

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.

Solution

TestScores.java

import java.util.Scanner;


public class TestScores {
   public TestScores(int a[]){
      
       try{
       double avg = average(a);
       }
       catch(IllegalArgumentException exp){
       System.out.println(exp) ;
       }
   }
   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();
          
       }
       new TestScores(a);
   }
   public static double average(int a[]) throws IllegalArgumentException{
       int sum = 0;
      
           for(int i=0; i<a.length; i++){
           if(a[i] < 0 || a[i] > 100){
               throw new IllegalArgumentException(\"Invalid Test Score\");
           }
           sum = sum + a[i];  
           }
           double average = sum/(double)a.length;
           System.out.println(\"Average is \"+average);
       return average;  
   }

}

IllegalArgumentException.java


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

Output:

Enter number of scores:
5
Enter score:
40
Enter score:
50
Enter score:
60
Enter score:
70
Enter score:
80
Average is 60.0

Enter number of scores:
5
Enter score:
50
Enter score:
607
Enter score:
110
Enter score:
90
Enter score:
90
Invalid Test Score

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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site