您的代码有正确的意图,但有些事情的顺序有点不对劲,而且目前存在语法问题。
我主张将您的代码拆分为两种方法(除非根据分配明确禁止您这样做)。一种从用户那里获取成绩的方法,另一种方法是对成绩求和。这样做的原因是您最终尝试同时存储和汇总成绩(这在技术上更有效),但这并没有教您如何通过迭代数组来计算运行总数(很可能是本课的重点)。
我要指出的另一件事(这可能超出了您现在在课程中的位置),即当您使用扫描仪时,您需要验证用户是否输入了您认为的内容我打字了。您希望用户输入一个数字,然后他们输入“Avocado”,这是完全合理的。因为Java是强类型的,这会导致你的程序抛出异常并崩溃。我已经添加了一些基本的输入验证作为如何做到这一点的示例;总体思路是:
1) 检查 Scanner 是否有一个 int
2)如果没有int,请用户再试一次
3)否则,它有一个 int ,你可以继续。存储值。
关于扫描仪的最后一件事。 记得关闭它们!如果不这样做,您可能会在扫描程序继续运行时导致内存泄漏。
以下是我将如何修改您的代码以执行您想要的操作。如果有什么不明白的地方给我留言,我会进一步解释。我将 cmets 留在内联,因为我认为这更容易消化!
package executor;
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Initial prompt to the user
System.out.println("Hello Drews, how many total grades do you want to process?");
// This loop validates that the user has actually entered an integer, and prevents
// an InputMismatchException from being thrown and blowing up the program.
int numberOfGrades = 0;
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
// If the program makes it through the while loop, we know that the Scanner has an int, and can assign it.
numberOfGrades = keyboard.nextInt();
// Creating the array using the method getGrades().
int[] storedGrades = getGrades(numberOfGrades, keyboard);
// Calculating the total score using the method getTotalScore().
int totalScore = getTotalScore(storedGrades);
System.out.println("Total Score is: " + totalScore);
keyboard.close();
}
/**
* Asks the user to provide a number of grades they wish to sum.
* @param numberOfGrades the total number of grades that will be requested from the user.
* @param keyboard the scanner that the user will use to provide the grades.
* @return the summed grades as an int.
*/
public static int[] getGrades(int numberOfGrades, Scanner keyboard) {
int[] grades = new int[numberOfGrades];
// Asking the user i number of times, to enter a grade to store.
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ":");
// More input validation to ensure the user can't store "Cat."
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
int userEnteredGrade = keyboard.nextInt();
// Storing the user's entry.
grades[i] = userEnteredGrade;
}
return grades;
}
/**
* Sums all of the grades stored within an integer array.
* @param storedGrades the grades to be summed.
* @return the total value of summed grades.
*/
public static int getTotalScore(int[] storedGrades) {
int totalScore = 0;
for (int i = 0; i < storedGrades.length; i++) {
totalScore += storedGrades[i];
}
return totalScore;
}
}