当我运行我的程序并选择0到100之间的数字时,它会错误地打印我的答案。
Java控制台
----jGRASP exec: java TestScores How many tests do you have? 3 Enter grade for Test 1: 80 Enter grade for Test 2: 80 Enter grade for Test 3: 80 The average is: 26.666666666666668The average is: 53.333333333333336The average is: 80.0 ----jGRASP: operation complete.
import java.util.Scanner;
public class TestScores {
public static void main(String[] args)
{
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
int check = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index] > 100)
{
try
{
throw new InvalidTestScore();
}
catch (InvalidTestScore e)
{
e.printStackTrace();
}
break;
}
}
for (int index = 0; index < grade.length; index++) {
totGrades += grade[index];
average = totGrades / grade.length;
System.out.print("The average is: " + average);
}
}
}
public class InvalidTestScore extends Exception
{
public InvalidTestScore()
{
super(" Error: Enter a number between 0 and 100");
}
}
答案 0 :(得分:3)
您可以在循环内打印计算平均值的平均值。
仅在循环外打印。
答案 1 :(得分:1)
你应该在循环中计算sum,然后(在循环之后)除以元素的数量。
答案 2 :(得分:0)
我将从循环内部计算总和的语句移动到外部,这是有效的。
我的新代码是。
import java.util.Scanner;
公共类TestScores
{
public static void main(String[]args)
{
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
int check = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index]> 100)
{
try
{
throw new InvalidTestScore();
}
catch (InvalidTestScore e)
{
e.printStackTrace();
}
break;
}
}
for (int index = 0; index < grade.length; index++)
{
totGrades += grade[index];
}
average = totGrades/grade.length;
System.out.print("The average is: " + average);
}
}
公共类InvalidTestScore扩展了Exception { public InvalidTestScore() { super(“错误:输入0到100之间的数字”); } }
你可以关闭我的帖子。