我正在尝试完成 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 anIllegalArgumentException
. Demonstrate. I need a file namedTestScores
andTestScoresDemo
.
这就是我目前所拥有的。我知道其中有些错误,我需要帮助修复它:
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/