Programming Using Java Unit 4 Assignment


Programming Using Java

Unit 4 Assignment


Programming Using Java


WEEK 3 ASSIGNMENT PROGRAMMING USING JAVA


Problem

Design a TestScores class that has fields to hold three test scores. The class should have a constructor, getter and setter methods for the test score fields, and a method that returns the average of the test scores. Demonstrate the class by writing a separate class UseTestScores which has main() that creates an instance of the TestScores class. And your program should ask the user to enter three test scores, which will be stored in the TestScores object. Then the program should display the average of the scores, as reported by the TestScores object.


Solution


TestScores.java


public class TestScores {

    private int[] scores;


    // constructor

    public TestScores(int[] scores) {

        this.scores = scores;

    }


    // getter for scores field

    public int[] getScores() {

        return scores;

    }


    // setter for scores field

    public void setScores(int[] scores) {

        this.scores = scores;

    }


    // method that returns the average of the test scores

    public double getAverage() throws IllegalArgumentException {

        int sum = 0;

        for (int score : scores) {

            if (score < 0 || score > 100) { // check if score is within range

                throw new IllegalArgumentException("Score must be between 0 and 100");

            }

            sum += score;

        }

        return (double) sum / scores.length;

    }

}{codeBox}


UseTestScores.java


import java.util.*;


public class UseTestScores {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);


        // ask user to enter three test scores

        System.out.print("Enter three test scores separated by spaces: ");

        int[] scores = new int[3];

        for (int i = 0; i < 3; i++) {

            scores[i] = input.nextInt();

        }


        // create TestScores object

        TestScores testScores = new TestScores(scores);


        // display the average of the scores

        try {

            System.out.printf("The average score is %.2f", testScores.getAverage());

        } catch (IllegalArgumentException e) {

            System.out.println(e.getMessage());

        }

    }

}{codeBox}


This program asks the user to enter three test scores, creates a TestScores object with those scores, and then displays the average of the scores using the getAverage() method of the TestScores class. In case a score is less than 0 or greater than 100, an IllegalArgumentException will be thrown.


Output


D:\Java>java UseTestScores

Enter three test scores separated by spaces: 15 20 25

The average score is 20.00{codeBox}






Post a Comment