我制作了一个能够接受教师输入的代码,这样他们就可以计算出他们班级的平均成绩,还有一些其他的东西。
不幸的是,我的代码没有正常工作。我试图让它显示平均等级,但它不断产生错误信息。
我需要代码首先获取类大小。然后记下学生的姓名和成绩。
然后应该计算班级的平均成绩。这就是我到目前为止所做的:
package program;
import java.util.Scanner;
public class FinalGrades{
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("How many students are in your class? ");
int totalStudents = Integer.parseInt(input.nextLine());
String[] names = new String[totalStudents];
double[] scores = new double[totalStudents];
for(int i = 0; i < totalStudents; i++){
System.out.print("Name: ");
names[i] = input.next();
System.out.print("Score: ");
scores[i] = input.nextDouble();
}
double avg = 0;
double sum = 0;
for (int j = 0; j<= totalStudents; j++){
sum += scores[j];
avg = sum/totalStudents;
System.out.println("The average score was: " + avg);
}
}
}
我还希望代码显示最高等级,旁边的学生姓名如下:
94.5,雅各布 (但现在没有必要)。答案 0 :(得分:3)
您的上次for
错误,您不会在那里计算avg
,但在for
完成后(在您获得sum
所有分数后) 。其次,在获得成绩后立即计算sum
。为了了解最高等级的学生,一旦给出输入,检查最高等级并记住它是否是最大等级。由于可以有多个这样的学生具有相同的最佳成绩,所以保留他们在阵列中的位置。
ArrayList<Integer> bestStudentPosition = new ArrayList<Integer>();
ArrayList<Integer> worstStudentPosition = new ArrayList<Integer>();
double maxGrade = 0;
double minGrade = 101;
double avg = 0;
double sum = 0;
for(int i = 0; i < totalStudents; i++){
System.out.print("Name: ");
names[i] = input.next();
System.out.print("Score: ");
scores[i] = input.nextDouble();
sum += scores[i];
System.out.println("Running avg: " + (sum / (i + 1)); // for extra points
if (scores[i] > maxGrade) {
bestStudentPosition.clear(); // delete all previous students from list
maxGrade = scores[i];
bestStudentPosition.add(new Integer(i));
}
else if (scores[i] == maxGrade) { // if its same as some student(s) before, add this one to list too
bestStudentPosition.add(new Integer(i));
} else if (scores[i] < minGrade) {
worstStudentPosition.clear();
minGrade = scores[i];
worstStudentPosition.add(new Integer(i));
} else if (scores[i] == minGrade) {
minGrade= scores[i];
worstStudentPosition.add(new Integer(i));
}
}
avg = sum/totalStudents; // final avg
System.out.println("The average score was: " + avg);
System.out.println("Best student(s):");
for (Integer position : bestStudentPosition) { // print all best students
System.out.println(maxGrade + ", " + names[position]);
}
System.out.println("Worst student(s):");
for (Integer position : worstStudentPosition) { // print all worst students
System.out.println(minGrade + ", " + names[position]);
}
答案 1 :(得分:1)
首先,您需要了解平均概念。它是总数的总和。
你正在做的是多次潜水。
double avg = 0;
double sum = 0;
for (int j = 0; j < totalStudents; j++){
sum += scores[j];
}
avg = sum/totalStudents;
System.out.println("The average score was: " + avg);
如果你想要一个平均值,你需要做:
double avg = 0;
double sum = 0;
for (int j = 0; j < totalStudents; j++){
sum += scores[j];
avg += scores[j] / totalStudents;
System.out.println("The average score was: " + avg);
}