3用Java编写一个学生 类student,包含的属性有学号、姓名、性别、年龄等,将所有学生存储在一个数组中,编写学生管理程序实现如下操作: (1)增加一个学生; (2)根据学号删除某个学生; (3)将所有学生年龄增加一岁; (4)按数组中顺序显示所有学生信息; (5)将所有学生按姓名排序输出。
时间: 2023-05-28 19:07:09 浏览: 333
c++定义一个学生类(属性有学号,姓名,成绩),要求输入学生的学号,姓名及三科的成绩,以输入内容来设置学生对象的属性。最后输出学生的学号,姓名及三科的平均成绩。
```java
public class Student implements Comparable<Student> {
private String id; // 学号
private String name; // 姓名
private String gender; // 性别
private int age; // 年龄
public Student(String id, String name, String gender, int age) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
}
// getter and setter methods
public void increaseAge() {
age++;
}
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) {
return this.name.compareTo(o.name);
}
}
public class StudentManager {
private Student[] students;
private int size;
public StudentManager(int capacity) {
students = new Student[capacity];
size = 0;
}
public void addStudent(Student student) {
if (size >= students.length) {
System.out.println("Error: Student array is full.");
return;
}
students[size++] = student;
}
public void deleteStudent(String id) {
for (int i = 0; i < size; i++) {
if (students[i].getId().equals(id)) {
for (int j = i + 1; j < size; j++) {
students[j - 1] = students[j];
}
students[--size] = null;
return;
}
}
System.out.println("Error: Student not found.");
}
public void increaseAge() {
for (int i = 0; i < size; i++) {
students[i].increaseAge();
}
}
public void showStudents() {
for (int i = 0; i < size; i++) {
System.out.println(students[i]);
}
}
public void sortByName() {
Arrays.sort(students, 0, size);
}
}
public class Main {
public static void main(String[] args) {
StudentManager manager = new StudentManager(10);
manager.addStudent(new Student("1001", "张三", "男", 18));
manager.addStudent(new Student("1002", "李四", "女", 19));
manager.addStudent(new Student("1003", "王五", "男", 20));
manager.showStudents();
System.out.println("--------");
manager.deleteStudent("1002");
manager.showStudents();
System.out.println("--------");
manager.increaseAge();
manager.showStudents();
System.out.println("--------");
manager.sortByName();
manager.showStudents();
}
}
```
阅读全文