當我運行我的程序並選擇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");
}
}
我想讓我的程序打印一行和正確的數量。 – lonesarah 2011-02-22 16:58:01
`嘗試{thow new Ex(); } catch(Ex e){e.printStackTrace()}```````必須是我見過的例外中最令人震驚,令人難以置信的濫用行爲之一。另外,你的格式是......我們只是說,明智地使用空白可以幫助你閱讀,但是你可以做得更多。 – delnan 2011-02-22 17:02:19