用Java编3-5编写一个学生类student,包含的属性有学号,姓名、性别、年龄等,将所有学生存储在一个数组中,编写学生管理程序实现如下操作: (1)增加一个学生; (2)根据学号删除某个学生;(3)将所有学生年龄增加一岁﹔ (4)按数组中顺序显示所有学生信息﹔(5)将所有学生按姓名排序输出。
时间: 2023-05-29 12:03:10 浏览: 135
```
public class Student implements Comparable<Student>{
private int id;
private String name;
private char gender;
private int age;
public Student(int id, String name, char gender, int age) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
}
//getter and setter methods
@Override
public int compareTo(Student s) {
return this.name.compareTo(s.getName());
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", gender=" + gender +
", age=" + age +
'}';
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class StudentManager {
private ArrayList<Student> students;
public StudentManager() {
students = new ArrayList<>();
}
public void addStudent(Student student) {
students.add(student);
}
public void removeStudent(int id) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() == id) {
students.remove(i);
break;
}
}
}
public void increaseAge() {
for (Student student : students) {
student.setAge(student.getAge() + 1);
}
}
public void displayStudents() {
for (Student student : students) {
System.out.println(student);
}
}
public void sortByName() {
Collections.sort(students);
}
public static void main(String[] args) {
StudentManager manager = new StudentManager();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("1. Add student");
System.out.println("2. Remove student by id");
System.out.println("3. Increase age of all students");
System.out.println("4. Display all students");
System.out.println("5. Sort students by name");
System.out.println("0. Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter student id:");
int id = scanner.nextInt();
System.out.println("Enter student name:");
String name = scanner.next();
System.out.println("Enter student gender:");
char gender = scanner.next().charAt(0);
System.out.println("Enter student age:");
int age = scanner.nextInt();
Student student = new Student(id, name, gender, age);
manager.addStudent(student);
break;
case 2:
System.out.println("Enter student id:");
int removeId = scanner.nextInt();
manager.removeStudent(removeId);
break;
case 3:
manager.increaseAge();
break;
case 4:
manager.displayStudents();
break;
case 5:
manager.sortByName();
break;
case 0:
System.exit(0);
break;
default:
System.out.println("Invalid choice!");
break;
}
}
}
}
```
阅读全文