我正在从网站上进行 Java 编程练习。我必须使用数组显示这个输出。
Enter the number of students: 3
Enter the grade for student 1: 55
Enter the grade for student 2: 108
Invalid grade, try again...
Enter the grade for student 2: 56
Enter the grade for student 3: 57
The average is 56.0
到目前为止,这是我的源代码。它显示结果但无法正常工作。第一个学生需要学生人数和年级。但是然后它停止了,如果我按任何数字并按 Enter,它会要求下一个年级等等。这样它在最后打印平均值。如果我输入不允许的输入,它会捕捉到它。这段代码有什么问题。
package array;
import java.util.Scanner;
public class GradesAverage {
public static void main(String[] args) {
int numStudents, sum=0;
int[] grades;
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students : ");
numStudents = in.nextInt();
grades = new int[numStudents];
//System.out.println(grades.length);
for (int i = 0; i < numStudents; i++) {
System.out.print("Enter grade of student "+i+" :");
grades[i] = Integer.parseInt(in.next());
if(grades[i]>100 || grades[i]<0)
{
System.out.println("It is not a valid number!");
i--;
continue;
}
//grades[i] = Integer.parseInt(in.next());
sum+=grades[i];
}
System.out.print("Average grades are: "+sum/numStudents);
in.close();
}
}