프로그램을 실행하고 0에서 100 사이의 숫자를 선택하면 내 대답이 잘못 인쇄됩니다.내 프로그램 print 문이 잘못되었습니다
----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
'시도해보십시오. 새 Ex(); } catch (Ex e) {e.printStackTrace()}는 내가 본 예외 중 가장 심각하고 마음을 괴롭 히는 중대한 위반 중 하나 여야합니다. 또한 포맷팅은 공백을 현명하게 사용하면 가독성을 높일 수 있지만, 과용 할 수는 있습니다. – delnan
내부 루프를 살펴보십시오. 해당 루프를 실행할 때마다 인쇄하고 있습니다. 루프가 완료되면 외부로 인쇄해야합니다. – Troggy