Write a class named TestScores. The class constructor should accept an array of
ID: 668455 • 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 .
SAMPLE RUN #1
Interactive Session
Enter number of test scores:5
Enter test score 1:70
Enter test score 2:65
Enter test score 3:94
Enter test score 4:55
Enter test score 5:90
74.8
Interactive Session
Enter number of test scores:6
Enter test score 1:100
Enter test score 2:23
Enter test score 3:40
Enter test score 4:-2
Enter test score 5:45
Enter test score 6:69
Test scores must have a value less than 100 and greater than 0.
Explanation / Answer
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
class TestScore
{
public int[] testScore;
public TestScore(int[] testScore)
{
this.testScore = testScore;
}
public double getAverage()
{
int i=0,sum = 0;
for(i=0;i<testScore.length;i++)
{
sum = sum + testScore[i];
}
return (sum*1.0)/testScore.length;
}
}
/* Name of the class has to be "Main" only if the class is public. */
class Driver
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
System.out.println("Enter number of test scores: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
int[] testScore = new int[number];
int temp;
for(int i=0;i<number;i++)
{
System.out.println("Enter Test Score " + (i+1) +" :");
temp = input.nextInt();
if(temp<0)
{
System.out.println("Test scores must have a value less than 100 and greater than 0");
break;
}
testScore[i] = temp;
}
TestScore scores = new TestScore(testScore);
System.out.println(scores.getAverage());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.