Write a class named TestScores. The class constructor should accept an array of
ID: 3764853 • Letter: W
Question
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.
- Create a TestScoresDemo class.
-Create a double 1-D array called badScores with the following test scores : 97.5, 66.7, 88.0, 101.0, 99.0
-Create another array called goodScores with the following scores: 97.5, 66.7, 88.0, 100.0, 99.0
Create a TestScores object initialized with badScores.
Create a TestScores object initialized with goodScores.
OUTPUT---
- the message: "Invalid score found"
-give the position of the element and the score that was invalid.
-Give the average of the good grades to 2 decimal places
Explanation / Answer
package current;
public class TestScoresDemo {
public static void main(String[] args) {
try {
TestScores ts1 = new TestScores(new double[] {97.5, 66.7, 88.0, 101.0, 99.0});
System.out.println("Average: "+ts1.average());
} catch(IllegalArgumentException e) {
System.out.println(e.getMessage());
}
try {
TestScores ts2 = new TestScores(new double[] {97.5, 66.7, 88.0, 100.0, 99.0});
System.out.println("Average: "+ts2.average());
} catch(IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
class TestScores {
private double[] scores;
public TestScores( double[] scores) {
//validate scores
if(scores != null) {
for(int i = 0; i <scores.length; i++) {
if(scores[i] < 0 || scores[i] > 100)
throw new IllegalArgumentException("Invalid score found : Position : "+i+" score: "+scores[i] );
}
}
this.scores = scores;
}
public String average() {
String avgstr = "";
double total = 0;
double avg = 0;
if(scores != null) {
for(double sc: scores)
total += sc;
avg = total/ scores.length;
//format to 2 decimal places
avgstr =String.format("%.2f", avg);
}
return avgstr;
}
}
-------------output---------------
Invalid score found : Position : 3 score: 101.0
Average: 90.24
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.