gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:36:33 26 4
gpt4 key购买 nike

我正在尝试完成 Java 作业。这就是它的要求:

Write a class named 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. Demonstrate. I need a file named TestScores and TestScoresDemo.

这就是我目前所拥有的。我知道其中有些错误,我需要帮助修复它:

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

我知道赋值需要一个 try 语句,因为在我的书中我看到了 IllegalArgumentException。谁能帮我?我使用 Eclipse 作为 IDE。

最佳答案

您的 TestScores 类应该有两个成员:一个接受分数数组的构造函数和一个返回分数平均值的方法。如果测试分数超出范围,分配不完全清楚其中哪些应该抛出 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
}
}

您的 TestScoresDemo 类(class)走在正确的轨道上。它首先需要将一组分数收集到一个数组中。然后它应该构造一个 TestScores 对象。这是需要放在 try/catch block 中的内容,因为它可以抛出异常。然后您只需调用 getAverageScore() 并对结果做一些处理。

关于java - 这是使用 IllegalArgumentException 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10344187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com