简体   繁体   English

这是使用IllegalArgumentException的正确方法吗?

[英]Is this the correct way to use an IllegalArgumentException?

I'm trying to work on a Java assignment. 我正在尝试从事Java任务。 This is what it asks: 这是它要求的:

Write a class named TestScores . 写一个名为TestScores的类。 The class constructor should accept an array of the test scores as its argument. 类构造函数应该接受一组测试分数作为其参数。 The class should have a method that returns the average of the test scores. 该类应该有一个返回测试分数平均值的方法。 If an test score in the array is negative or greater than 100, the class should throw an IllegalArgumentException . 如果数组中的测试分数为负或大于100,则该类应抛出IllegalArgumentException Demonstrate. 演示。 I need a file named TestScores and TestScoresDemo . 我需要一个名为TestScoresTestScoresDemo的文件。

This is what I have so far. 这就是我到目前为止所拥有的。 I know some of it is wrong and I need help fixing it: 我知道其中有些是错的,我需要帮助修复它:

class TestScores {
    public static void checkscore(int s) {
        if (s<0) throw new IllegalArgumentException("Error: score is negative.");
        else if (s>100) throw new IllegalArgumentException("Error Score is higher then 100");
        else if (s>89)throw new IllegalArgumentException("Your grade is an A");
        else if (s>79 && s<90)throw new IllegalArgumentException("Your grade is an B");
        else if (s>69 && s<80)throw new IllegalArgumentException("Your grade is an C");
        else if (s>59 && s<70)throw new IllegalArgumentException("Your grade is an D");
        else if (s<60)throw new IllegalArgumentException("Your grade is an F");

        {
            int sum = 0; //all elements together
            for (int i = 0; i < a.length; i++)
                sum += a[i];
        }
        return sum / a.length;
    }
}

class TestScoresDemo {
    public static void main(String[] args) {
        int score = 0;
        Scanner scanner = new Scanner(System.in);
        System.out.print(" Enter a Grade number: ");
        String input = scanner.nextLine();
        score = Integer.parseInt(input);
        TestScores.checkscore(score);
        System.out.print("Test score average is" + sum);
    }
}

I know the assignment calls for a try statement because in my book that's what I see with the IllegalArgumentException . 我知道赋值调用了一个try语句,因为在我的书中我看到的是IllegalArgumentException Can anyone help me? 谁能帮我? I'm using Eclipse as an IDE. 我正在使用Eclipse作为IDE。

Your TestScores class should have two members: a constructor that accepts an array of scores and a method that returns the average of the scores. 您的TestScores类应该有两个成员:一个接受一组分数的构造函数和一个返回分数平均值的方法。 The assignment isn't totally clear as to which of these should throw an IllegalArgumentException if a test score is out of range, but I'd make it the constructor (since that's what has the argument). 如果测试分数超出范围,那么分配中的哪一个应该抛出IllegalArgumentException并不完全清楚,但是我将它作为构造函数(因为那是参数)。

public class TestScores {
    public TestScores(int[] scores) throws IllegalArgumentException {
        // test the scores for validity and throw an exception if appropriate
        // otherwise stash the scores in a field for later use
    }

    public float getAverageScore() {
        // compute the average score and return it
    }
}

You're on the right track with your TestScoresDemo class. 您的TestScoresDemo课程正确。 It will first need to collect a set of scores into an array. 它首先需要将一组分数收集到一个数组中。 Then it should construct a TestScores object. 然后它应该构造一个TestScores对象。 This is what needs to be inside a try / catch block because it can throw an exception. 这是需要在try / catch块中的内容,因为它可以抛出异常。 Then you just need to call getAverageScore() and do something with the result. 然后你只需要调用getAverageScore()并对结果做一些事情。

An exception is something used to define something that didn't go right on the normal flow of an application. 例外是用于定义在应用程序的正常流程上不正确的事情。 You have to throw the IllegalArgumentException when the method checkScore is called and it finds any argument outside the range (between 0 and 100). 调用方法checkScore时,必须抛出IllegalArgumentException,并且它会在范围之外找到任何参数(介于0和100之间)。

Your class should have this structure: 你的班级应该有这样的结构:

public class TestScore {

    private int scores[]; //With setters and getters.

    public TestScore(int scores[]) {
        //Here, you set the scores array to the one on this class.
    }

    public int getAverage() {
        //You do the average here, and since you need to iterate over the 
        //array to sum each value, you can check the value and if it's not
        //ok you throw the IllegalArgumentException. No throws keyword
        //required since this kind of exception (like NullPointerException
        //and many others) are unchecked exceptions, meaning they can be 
        //thrown by a method and it does not need to specify them.
    }

}

The test class should create a TestScore object with an int array as a parameter of its constructor. 测试类应创建一个TestScore对象,其int数组作为其构造函数的参数。 Then you make a testAverageScore method that has the try-catch statement on it, since it's required to call the getAverage method. 然后你创建一个testAverageScore方法,它上面有try-catch语句,因为它需要调用getAverage方法。

Hope that helps. 希望有所帮助。 Good luck!. 祝好运!。

EDIT: IllegalArgumentException is an unchecked exception. 编辑: IllegalArgumentException是一个未经检查的异常。

public class TestScores {
private final int[] scores;

public TestScores(int[] scores) {
    this.scores = scores;
}

public int getAverage() {
    int sum = 0;

    if(scores.length == 0) {
        return 0;
    }

    for(int score: scores) {
        if(score < 0 || score > 100) {
            throw new IllegalArgumentException("Score is not valid!");
        }
        sum += score;
    }
    return sum/scores.length;
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM