我需要创建一个程序来计算用户输入的测试分数的平均值。这实际上是我第二次有人要求制作这个节目。但是这次分配要求我在用户输入小于0或大于100的testscore时抛出IllgalArgumentException。问题是即使测试分数在0到100之间,无论什么测试分数,程序都会崩溃,并且会出现IllegalArgumentException。 。不知道我做错了什么想法这里没有例外的预期输出
预期输出
Enter number of test scores:5
Enter test score 1:70
Enter test score 2:65
Enter test score 3:94
Enter test score 4:55
Enter test score 5:90
74.8
和我的代码
public static void main(String[] args) throws IllegalArgumentException
{
Scanner input = new Scanner (System.in);
int numTests = 0;
int [] grade = new int [numTests];
double average;
double totalGrades = 0;
System.out.print("Enter number of test scores:");
numTests = input.nextInt();
grade = new int[numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter test score " + (index + 1) + ":");
grade[index] = input.nextInt();
if(grade[index] < 0 || grade[index] > 100);
{
throw new IllegalArgumentException();
}
}
for (int i = 0; i < grade.length; i++)
{
totalGrades += grade[i];
}
average = totalGrades / grade.length;
System.out.println(average);
}
private static class IllegalArgumentException extends Exception
{
public IllegalArgumentException()
{
super("Test scores must have a value less than 100 and greater than 0.");
}
public IllegalArgumentException(int value)
{
super("Invalid Test Score: " + value);
}
}
答案 0 :(得分:5)
if(grade[index] < 0 || grade[index] > 100);
{
throw new IllegalArgumentException();
}
;
行末尾的if
表示无条件执行throw
,因为它不在条件块中。
您的代码(有效)与:
相同if(grade[index] < 0 || grade[index] > 100) { /* do nothing */ }
throw new IllegalArgumentException();
删除;
。