Ale*_*ria 7 java exception illegalargumentexception
我正在尝试从事Java任务.这是它要求的:
写一个名为的类
TestScores.类构造函数应该接受一组测试分数作为其参数.该类应该有一个返回测试分数平均值的方法.如果数组中的测试分数为负或大于100,则该类应该抛出一个IllegalArgumentException.演示.我需要一个名为TestScoresand 的文件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);
}
}
Run Code Online (Sandbox Code Playgroud)
我知道作业需要一个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
}
}
Run Code Online (Sandbox Code Playgroud)
你的TestScoresDemo班级正走在正确的轨道上。它首先需要将一组分数收集到一个数组中。然后它应该构造一个TestScores对象。try这是/块内需要的内容,catch因为它可能引发异常。然后你只需要调用getAverageScore()并处理结果即可。
| 归档时间: |
|
| 查看次数: |
89459 次 |
| 最近记录: |