java - 无法抛出 IllegalArgumentException

标签 java exception throw throws

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

最佳答案

您就快成功了...如果您确保所有分数都在正确的范围内。

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.");
}

关于java - 无法抛出 IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21924955/

相关文章:

java - Jasper 报告语法 报告元素和框架

java - 在另一个中编译类时出现编译错误

java - 如何记录spring boot jar文件异常

Java,防止类调用公共(public)方法

java - 仅当没有抛出异常时如何执行代码块

c++ - 使用 Define 抛出异常

java - XMLBeans-xsi :type stripped using Axis2 and Tomcat?

spring - 将某些异常排除在报告给 Sentry 之外

c++ - 为什么我的程序不执行第二个 catch block ?

Java lambda 只抛出表达式样式而不是语句样式