
本文将详细介绍如何计算一个对象数组的平均值,其中对象包含字符串和整数变量。我们将以一个学生类为例,该类包含姓名(字符串)和分数(整数)。通过示例代码,我们将演示如何遍历数组,提取分数,计算总和,并最终计算出平均分。同时,我们还会展示如何找到数组中的最高分。
首先,我们需要定义一个 Student 类,该类包含学生的姓名和分数两个属性。
import java.util.Scanner;
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() {
return this.name;
}
public int getScore() {
return this.score;
}
}注意:
接下来,我们需要定义一个 TestReporter 类,该类负责管理学生数组,计算平均分和最高分,并显示结果。
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() {
double total = 0;
highestScore = 0; // 初始化最高分
for (int i = 0; i < numOfStudents; i++) {
int score = ourClass[i].getScore();
total += score; // 累加分数
if (score > highestScore) {
highestScore = score; // 更新最高分
}
}
averageScore = total / ourClass.length;
}
public void displayResults() {
computeStats(); // 先计算统计数据
for (Student student: ourClass) {
student.writeOutput();
}
System.out.println("Average Score = " + averageScore);
System.out.println("Highest Score = " + highestScore);
}
public static void main(String[] args) {
TestReporter reporter = new TestReporter();
reporter.getData();
reporter.displayResults();
}
}代码解释:
编译并运行 TestReporter 类,程序会提示您输入学生人数,然后依次输入每个学生的姓名和分数。最后,程序会显示每个学生的信息,以及平均分和最高分。
通过以上步骤,我们成功地计算了包含字符串和整数变量的对象数组的平均值和最高值。这个例子展示了如何遍历对象数组,访问对象的属性,并进行相应的计算。 这个方法可以推广到其他类型的对象数组,只需要修改对象类的定义和计算逻辑即可。
以上就是计算包含字符串和整数变量的对象数组的平均值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号