70.6k views
4 votes
Write an exception class named InvalidTestScore. Modify the TestScores class you wrote in Part I 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 subclass 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 test scores. If the average method throws an InvalidTestScore exception, the main method should catch it and print "Invalid test score."

1 Answer

2 votes

Answer:

See Explaination

Step-by-step explanation:

package testscores;

import java.util.ArrayList;

import java.util.List;

public class TestScores {

public List<Integer> scorearray=new ArrayList<>();

public TestScores(List<Integer> scores) throws InvalidTestScore{

this.scorearray=scores;

for(int i=0;i<scorearray.size();i++){

if(scorearray.get(i)>100 || scorearray.get(i)<0){

throw new InvalidTestScore(this.scorearray.get(i));

}

}

}

public double average(){

int tot=0;

for(int i=0;i<this.scorearray.size();i++){

tot=tot+this.scorearray.get(i);

}

return tot*(1.0)/(this.scorearray.size());

}

class InvalidTestScore extends Exception

{

private double amount;

public InvalidTestScore(int Score)

{

System.out.println("Invalid Score "+Score);

}

}

}

User MacAnthony
by
5.4k points