TestScores class program

The problem

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 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.

Breaking it down

TestScores Class

public class TestScores {

    private double score1;
    private double score2;
    private double score3;

    public TestScores(double score1, double score2, double score3) {
        this.score1 = score1;
        this.score2 = score2;
        this.score3 = score3;
    }

    public void setScore1(double score) {
        score1 = score;
    }

    public void setScore2(double score) {
        score2 = score;
    }

    public void setScore3(double score) {
        score3 = score;
    }

    public double getScore1() {
        return score1;
    }

    public double getScore2() {
        return score2;
    }

    public double getScore3() {
        return score3;
    }

    public double getAverageScore() {
        return (score1 + score2 + score3) / 3;
    }
}

Main program

public static void main(String[] args) {

    double test1;
    double test2;
    double test3;

    // Create a scanner for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    System.out.print("Enter test score: ");
    test1 = keyboard.nextDouble();

    System.out.print("Enter test score: ");
    test2 = keyboard.nextDouble();

    System.out.print("Enter test score: ");
    test3 = keyboard.nextDouble();

    // close scanner
    keyboard.close();

    TestScoresClassProgram classProgram = new TestScoresClassProgram();
    TestScores scores = classProgram.new TestScores(test1, test2, test3);

    // Display average
    System.out.println("The average test score: "
            + scores.getAverageScore());
}

Output

Enter test score: 10
Enter test score: 30
Enter test score: 25
The average test score: 21.666666666666668

Level Up

  • Add a test score 4, 5, 6. Is this TestScores class flexible to continue to add scores? Modify the program to accept values and add scores to a list.
  • Format the average test score to 2 decimal points.
  • Convert the average test score to a grade scale using guava range map