如何计算含字符串与整数属性的对象数组的平均值及最高分?
问题解决:从Student对象提取分数计算平均值和最高分
你的代码存在两个核心问题:Student类的Getter方法逻辑错误,以及TestReporter中直接操作Student对象而非提取分数,下面一步步修正:
1. 修正Student类的Getter方法
你的getName和getScore方法带了不必要的参数,且getScore返回的是传入参数而非对象自身的score属性,这会导致无法正确获取学生分数。修改为无参的正确Getter:
public class Student { private String name; private int score; public Student() { } public Student(String name, int score){ this.name = name; this.score = score; } public void setName(String name) { this.name = name; } public void setScore(int score) { this.score = score; } public void readInput() { Scanner keyboard = new Scanner(System.in); System.out.println("Please enter the student's name: "); this.name = keyboard.next(); System.out.println("Please enter the student's score: "); this.score = keyboard.nextInt(); } public void writeOutput() { System.out.println("The student's name and score: " + name + ", " + score + "%"); } // 修正:去掉参数,返回对象自身的name public String getName() { return this.name; } // 修正:去掉参数,返回对象自身的score public int getScore() { return this.score; } }
2. 修正TestReporter的computeStats方法
现在可以通过getScore()方法从Student对象中提取分数,同时在遍历过程中计算总分、平均值和最高分:
import java.util.Scanner; public class TestReporter { private int highestScore; private double averageScore; private Student[] ourClass; private int numOfStudents; public TestReporter(){ } public void getData() { Scanner keyboard = new Scanner(System.in); System.out.println("Please enter the number of students"); numOfStudents = keyboard.nextInt(); ourClass = new Student[numOfStudents]; for (int i = 0; i < numOfStudents ; i++) { ourClass[i] = new Student(); ourClass[i].readInput(); } } public void computeStats() { if (numOfStudents == 0) { averageScore = 0; highestScore = 0; return; } double total = 0; // 初始化最高分为第一个学生的分数 highestScore = ourClass[0].getScore(); for (int i = 0; i < numOfStudents; i++) { int currentScore = ourClass[i].getScore(); total += currentScore; // 更新最高分 if (currentScore > highestScore) { highestScore = currentScore; } } averageScore = total / numOfStudents; } public void displayResults() { System.out.println("=== Student List ==="); for (Student student: ourClass) { student.writeOutput(); } System.out.println("\n=== Class Stats ==="); System.out.println("Average Score: " + String.format("%.2f", averageScore) + "%"); System.out.println("Highest Score: " + highestScore + "%"); } // 测试用主方法 public static void main(String[] args) { TestReporter reporter = new TestReporter(); reporter.getData(); reporter.computeStats(); reporter.displayResults(); } }
关键修正点说明
- 通过
ourClass[i].getScore()获取每个学生的分数,才能进行数值计算 - 初始化最高分后,遍历每个学生的分数进行比较更新
- 增加空数组判断,避免数组为空时出现异常
- 在
displayResults中新增统计结果输出,让功能更完整
内容的提问来源于stack exchange,提问作者dumbkidincollege
相关产品推荐
相关产品推荐

