我需要程序接受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
答案 0 :(得分:2)
语法是
if (condition) {
throw new IllegalArgumentException("message here");
}
答案 1 :(得分:2)
你几乎就在那里......在if
你确保所有分数都在适当的范围内。
当if
失败时,您希望在else
中抛出IllegalArgumentException,如下所示:
if (scores[0] >= 0 && scores[0] <= 100 ||
scores[1] >= 0 && scores[1] <= 100 ||
scores[2] >= 0 && scores[2] <= 100)
{
average = totalScores / 3;
System.out.println("Average Score: " + average);
}
else
{
throw new IllegalArgumentException("Numbers were too low or high.");
}
答案 2 :(得分:1)
它可以捕获应用程序在try
块中抛出异常的异常。
在try
块中,我们只看到average = totalScores / 3;
,它不会抛出任何异常。所以它没有抓到被抛出的任何东西。
您可以使用此功能抛出异常 - IllegalArgumentException
。
public static int getInputScore(Scanner keyboard) {
int score = keyboard.nextInt();
if (score < 0 || score >= 100) {
throw new IllegalArgumentException();
}
return score;
}
并在main
代码中使用它:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] scores = new int[3];
System.out.println("Score 1:");
try {
scores[0] = getInputScore(keyboard);
} catch (IllegalArgumentException e) {
System.out.println("Numbers were too low or high.");
return;
}
System.out.println("Score 2:");
try {
scores[1] = getInputScore(keyboard);
} catch (IllegalArgumentException e) {
System.out.println("Numbers were too low or high.");
return;
}
System.out.println("Score 3:");
try {
scores[2] = getInputScore(keyboard);
} catch (IllegalArgumentException e) {
System.out.println("Numbers were too low or high.");
return;
}
int totalScores = scores[0] + scores[1] + scores[2];
int average = totalScores / 3;
System.out.println("Average Score: " + average);
}