Problem
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}