java 如何计算一个包含字符串和整型变量的对象数组的平均值?

myzjeezk  于 2022-11-20  发布在  Java
关注(0)|答案(1)|浏览(134)

这是我目前拥有的代码。
下面是我的对象“学生”

`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 + "%");
    }
    
    public String getName(String name) {
        return this.name;
    }
    public int getScore(int score) {
        return score;
    }
}`

然后在另一个类“TestReporter”中,我尝试计算ourClass[]数组的平均值。
我也要在ourClass数组中找到最高分数,但不知道如何将分数与学生分开,我可能使问题过于复杂,但任何帮助都将不胜感激。
'导入java.lang.reflect.数组;导入java.util.Arrays;导入java.util.Scanner;
公共类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() {
    double total = 0;
    for (int i = 0; i < numOfStudents; i++) {
        total = total + ourClass[i];
    }
    averageScore = total / ourClass.length;

    
}

public void displayResults() {
    
    for (Student Student: ourClass) {
        Student.writeOutput();
    }
}

}`

bz4sfanl

bz4sfanl1#

要获取计算StateStats中的最高得分声明变量

public void computeStats() {
    double total = 0;
   int highestScore = 0;

    for (int i = 0; i < numOfStudents; i++) {
        int score = ourClass[i].getScore();
        total = total;
        if(score > highestScore)
           highestScore =  score;

    }
    averageScore = total / ourClass.length;
    System.output.println("Average Score = "+averageScore;
    System.output.println("Highest Score = " highestScore;
    
}

然后将以下内容添加到displayResults()

computeStats();

**另外:**按照{QBrute}所述更改Setter

相关问题