java编写一个学生类student,包含的属性有学号、姓名、性别、年龄等,将所有学生存储 在一个数组中,编写学生管理程序实现如下操作: (1)增加一个学生; (2)根据学号删除某个学生; (3)将所有学生年龄增加一岁; (4)按数组中顺序显示所有学生信息; (5)将所有学牛按姓名排序输出。
时间: 2023-05-29 20:04:05 浏览: 723
public class 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;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class StudentManager {
private Student[] students;
private int size;
public StudentManager(int capacity) {
students = new Student[capacity];
size = 0;
}
public boolean add(Student student) {
if (size == students.length) {
return false;
}
students[size++] = student;
return true;
}
public boolean remove(String id) {
int index = -1;
for (int i = 0; i < size; i++) {
if (students[i].getId().equals(id)) {
index = i;
break;
}
}
if (index == -1) {
return false;
}
for (int i = index; i < size - 1; i++) {
students[i] = students[i + 1];
}
students[--size] = null;
return true;
}
public void increaseAge() {
for (int i = 0; i < size; i++) {
students[i].setAge(students[i].getAge() + 1);
}
}
public void display() {
for (int i = 0; i < size; i++) {
System.out.println("学号:" + students[i].getId() + ",姓名:" + students[i].getName() + ",性别:" + students[i].getGender() + ",年龄:" + students[i].getAge());
}
}
public void sortByName() {
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (students[i].getName().compareTo(students[j].getName()) > 0) {
Student temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
display();
}
}
public class Test {
public static void main(String[] args) {
StudentManager manager = new StudentManager(5);
manager.add(new Student("1001", "张三", "男", 18));
manager.add(new Student("1002", "李四", "女", 19));
manager.add(new Student("1003", "王五", "男", 20));
manager.add(new Student("1004", "赵六", "女", 21));
manager.add(new Student("1005", "钱七", "男", 22));
manager.display();
System.out.println("------------------------------");
manager.remove("1003");
manager.display();
System.out.println("------------------------------");
manager.increaseAge();
manager.display();
System.out.println("------------------------------");
manager.sortByName();
}
}
阅读全文