Java 定义数组存储4个学生对象学生属性姓名性别年龄成绩计算出四名学生的平均成绩
时间: 2023-11-22 17:52:47 浏览: 72
java用list集合存储学生信息并算出成绩平均值操作
5星 · 资源好评率100%
可以使用 Java 中的类来定义学生对象,如下所示:
```java
public class Student {
private String name;
private String gender;
private int age;
private double score;
public Student(String name, String gender, int age, double score) {
this.name = name;
this.gender = gender;
this.age = age;
this.score = score;
}
public double getScore() {
return score;
}
}
```
然后,在主函数中定义一个数组,存储这四个学生对象,并计算平均成绩,如下所示:
```java
public static void main(String[] args) {
Student[] students = new Student[4];
students[0] = new Student("Tom", "Male", 18, 80);
students[1] = new Student("Jerry", "Female", 19, 90);
students[2] = new Student("Alice", "Female", 20, 85);
students[3] = new Student("Bob", "Male", 21, 75);
double totalScore = 0;
for (int i = 0; i < students.length; i++) {
totalScore += students[i].getScore();
}
double averageScore = totalScore / students.length;
System.out.println("The average score is " + averageScore);
}
```
以上代码中,我们首先定义了一个存储学生对象的数组 `students`,并初始化了其中的四个元素。然后,我们遍历数组,累加其中每个学生的成绩,最后计算平均成绩并输出。
阅读全文