创建一个对象数组,数组的元素是学生对象,学生信息包括学号姓名和成绩,求总人数和平均分
时间: 2024-05-08 07:22:31 浏览: 15
以下是一个示例代码,其中包含一个 `Student` 类来表示学生对象:
```java
public class Student {
private String id;
private String name;
private double score;
public Student(String id, String name, double score) {
this.id = id;
this.name = name;
this.score = score;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
}
```
然后,我们可以创建一个 `Student[]` 数组来存储学生对象,然后迭代数组并计算总人数和平均分:
```java
public static void main(String[] args) {
Student[] students = {
new Student("001", "张三", 80),
new Student("002", "李四", 90),
new Student("003", "王五", 70),
new Student("004", "赵六", 85)
};
int total = students.length;
double sum = 0;
for (Student student : students) {
sum += student.getScore();
}
double average = sum / total;
System.out.println("总人数:" + total);
System.out.println("平均分:" + average);
}
```
输出结果:
```
总人数:4
平均分:81.25
```