Design a TestScores class that has fields to hold three test scores. The class s
ID: 3817579 • Letter: D
Question
Design a TestScores class that has fields to hold three test scores. The class should have a constructor, accessor and mutator methods for the test score fields, and a method that returns the average of the test scores. Demonstrate the class by writing a separate program that creates an instance of the TestScores class. The program should ask the user to enter three test scores, which are stored in the TestScores object. Then the program should display the average of the scores, as reported by the TestScores object.Explanation / Answer
//TestScores.java
public class TestScores {
//Scores Attributes
int score1,score2,score3;
//Constructor
public TestScores(int score1,int score2,int score3){
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
}
//Accessors and Mutators
public int getScore1() {
return score1;
}
public void setScore1(int score1) {
this.score1 = score1;
}
public int getScore2() {
return score2;
}
public void setScore2(int score2) {
this.score2 = score2;
}
public int getScore3() {
return score3;
}
public void setScore3(int score3) {
this.score3 = score3;
}
//Method to calculate average of test scores
public double averageTestScores(){
//Return Average of test score
double total = this.getScore1()+this.getScore2()+this.getScore3();
return total/3;
}
}
//TestScoresMain.java
import java.util.Scanner;
public class TestScoresMain {
public static void main(String[] args) {
//Scanner for reading input
Scanner s = new Scanner(System.in);
System.out.println("Enter three scores:");
System.out.println("*******************");
//Reading Test score-1,2,3
System.out.println("Enter Test Score-1");
int score1 = s.nextInt();
System.out.println("Enter Test Score-2");
int score2 = s.nextInt();
System.out.println("Enter Test Score-3");
int score3 = s.nextInt();
//Creating TestScores instance
TestScores ts = new TestScores(score1,score2,score3);
//Printing Test Scores
System.out.println("Score-1:"+ts.getScore1()+",Score-2:"+ts.getScore2()+",Score-3:"+ts.getScore3());
//Calling averageTestScores method
double average = ts.averageTestScores();
//Printing Average
System.out.println("The average of Test Scores is:"+average);
}
}
Output:
javac TestScoresMain.java
java TestScoresMain
Enter three scores:
*******************
Enter Test Score-1
78
Enter Test Score-2
56
Enter Test Score-3
87
Score-1:78,Score-2:56,Score-3:87
The average of Test Scores is:73.66666666666667