0

我需要程序接受 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
4

3 回答 3

2

语法是

if (condition) {
    throw new IllegalArgumentException("message here");
}
于 2014-02-21T03:58:25.247 回答
2

你快到了……在你if确保所有分数都在适当的范围内。

if失败时,您想在 中抛出 IllegalArgumentException else,如下所示:

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.");
}
于 2014-02-21T04:01:02.753 回答
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);
}
于 2014-02-21T04:15:15.980 回答