Write a class named TestScores. The class constructor should accept an array of
ID: 3668807 • 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 Driver class in the same file). The program should ask the user to input the number of test scores to be counted, and then each individual test score. It should then make an array of those scores, create a TestScore object , and print the average of the scores. If an IllegalArgumentException is thrown, the main method should catch it, print "Test scores must have a value less than 100 and greater than 0." and terminate the program .
Explanation / Answer
TestScore.java
// header files
import java.util.Scanner;
// TestScore
public class TestScore{
public static void main(String args[]) throws Exception
{
// getting input from user
Scanner keyboard = new Scanner(System.in);
int array[] = new int[2];
System.out.println("Enter scores: ");
for(int i=0; i<2; i++)
array[i]=keyboard.nextInt();
// create object for class Scores
Scores t1 = new Scores(array);
System.exit(0);
}
}
Scores.java
// header files
import java.util.Scanner;
class Scores
{
// declare variable
private int score[]=new int[2];
public Scores(int test[])
{
try
{
for(int i=0; i<2; i++)
{
if(test[i]<0||test[i]>100){
throw new IllegalArgumentException("Number cannot be less than 0 and greater than 100");
}
else{
score[i]=test[i];
}
}
// display output
System.out.println("Average is: "+ average());
}
catch(IllegalArgumentException e)
{
System.out.println(e);
}
}
public double average()
{
int sum=0;
double avg;
for(int i=0;i<2;i++)
{
sum+=score[i];
}
avg=sum/2;
return avg;
}
}
Sample output
Enter scores:
45
50
Average is: 47.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.