我需要程序接受 3 个测试分数,然后打印它们的平均值,但如果分数小于 -1 或大于 100,它应该抛出 IllegalArgumentException。我可以打印出平均值,但是在测试 -1 或 101 时,它不会抛出异常。我究竟做错了什么?
我对学习异常非常陌生,因此感谢您提供任何帮助。
这是我的代码:
import java.util.Scanner;
import java.io.*;
public class TestScores
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int[]scores = new int [3];
System.out.println("Score 1:");
scores[0] = keyboard.nextInt();
System.out.println("Score 2:");
scores[1] = keyboard.nextInt();
System.out.println("Score 3:");
scores[2] = keyboard.nextInt();
int totalScores = scores[0] + scores[1] + scores[2];
int average = 0;
if (scores[0] >= 0 && scores[0] <= 100 ||
scores[1] >= 0 && scores[1] <= 100 ||
scores[2] >= 0 && scores[2] <= 100)
{
try
{
average = totalScores / 3;
}
catch(IllegalArgumentException e)
{
System.out.println("Numbers were too low or high.");
}
System.out.println("Average Score: " + average);
}
} //end of public static void
} //end of TestScores