设一个班有10名学生,每个学生有姓名、学号、成绩等信息,请利用对象数组的概念编程,求平均成绩java
时间: 2024-05-22 10:12:41 浏览: 109
class-string.rar_对象数组
假设学生信息存储在Student类中,可以按照如下方式编写代码:
public class Main {
public static void main(String[] args) {
Student[] students = new Student[10]; // 定义存储学生信息的数组
students[0] = new Student("张三", "201901", 80);
students[1] = new Student("李四", "201902", 85);
students[2] = new Student("王五", "201903", 90);
students[3] = new Student("赵六", "201904", 78);
students[4] = new Student("钱七", "201905", 92);
students[5] = new Student("孙八", "201906", 87);
students[6] = new Student("周九", "201907", 95);
students[7] = new Student("吴十", "201908", 83);
students[8] = new Student("郑一", "201909", 88);
students[9] = new Student("陈二", "201910", 91);
double totalScore = 0; // 总成绩
for (int i = 0; i < students.length; i++) {
totalScore += students[i].getScore(); // 累加每个学生的成绩
}
double averageScore = totalScore / students.length; // 平均成绩
System.out.println("平均成绩为:" + averageScore);
}
}
class Student {
private String name;
private String id;
private double score;
public Student(String name, String id, double score) {
this.name = name;
this.id = id;
this.score = score;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public double getScore() {
return score;
}
}
阅读全文