定义Student类。 要求: (1)在该类中包括有学号(自动编号)、姓名、爱好和平均绩点属性; (2)定义静态成员,用于对学生对象数量进行计数; (3)类中必须包含构造方法; (4)完成修改数据,显示数据,修改成绩,统计每个学生的平绩点操作。 (5)重载toString方法,用于对象属性值的输出。
时间: 2023-12-19 21:07:48 浏览: 64
好的,这是一个经典的面向对象编程问题,下面是一个可能的实现:
```java
public class Student {
private static int numOfStudents = 0; // 静态成员,用于对学生对象数量进行计数
private int id; // 学号,自动编号
private String name; // 姓名
private String hobby; // 爱好
private double gpa; // 平均绩点
public Student(String name, String hobby, double gpa) {
this.id = ++numOfStudents; // 自动编号
this.name = name;
this.hobby = hobby;
this.gpa = gpa;
}
// getter 和 setter 方法
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
// 修改数据
public void modify(String name, String hobby, double gpa) {
this.name = name;
this.hobby = hobby;
this.gpa = gpa;
}
// 显示数据
public void display() {
System.out.println("Id: " + id + ", Name: " + name + ", Hobby: " + hobby + ", GPA: " + gpa);
}
// 修改成绩
public void modifyGpa(double gpa) {
this.gpa = gpa;
}
// 统计每个学生的平均绩点
public static double averageGpa(Student[] students) {
double sum = 0;
for (int i = 0; i < students.length; i++) {
sum += students[i].gpa;
}
return sum / students.length;
}
// 重载toString方法
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", hobby='" + hobby + '\'' +
", gpa=" + gpa +
'}';
}
}
```
使用示例:
```java
public class Test {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("Tom", "reading", 3.8);
students[1] = new Student("Jerry", "swimming", 4.0);
students[2] = new Student("Alice", "singing", 3.5);
for (int i = 0; i < students.length; i++) {
students[i].display();
}
System.out.println("Average GPA: " + Student.averageGpa(students));
students[1].modify("Jerry2", "running", 3.9);
students[1].modifyGpa(4.1);
students[1].display();
System.out.println("Average GPA: " + Student.averageGpa(students));
}
}
```
输出结果:
```
Id: 1, Name: Tom, Hobby: reading, GPA: 3.8
Id: 2, Name: Jerry, Hobby: swimming, GPA: 4.0
Id: 3, Name: Alice, Hobby: singing, GPA: 3.5
Average GPA: 3.7666666666666666
Id: 2, Name: Jerry2, Hobby: running, GPA: 4.1
Average GPA: 3.8
```
阅读全文