编写一段学生管理系统的代码
时间: 2023-10-18 19:04:18 浏览: 64
好的,以下是一个简单的学生管理系统的代码示例,仅供参考:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class StudentManagementSystem {
private ArrayList<Student> students;
public StudentManagementSystem() {
students = new ArrayList<Student>();
}
public void addStudent(Student student) {
students.add(student);
}
public void removeStudent(int index) {
students.remove(index);
}
public void displayAllStudents() {
for (Student student: students) {
System.out.println(student.toString());
}
}
public void displayStudent(int index) {
System.out.println(students.get(index).toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StudentManagementSystem sms = new StudentManagementSystem();
boolean exit = false;
while (!exit) {
System.out.println("1. Add student\n2. Remove student\n3. Display all students\n4. Display student\n5. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter student name: ");
String name = scanner.next();
System.out.print("Enter student age: ");
int age = scanner.nextInt();
System.out.print("Enter student grade: ");
int grade = scanner.nextInt();
sms.addStudent(new Student(name, age, grade));
break;
case 2:
System.out.print("Enter student index to remove: ");
int index = scanner.nextInt();
sms.removeStudent(index);
break;
case 3:
sms.displayAllStudents();
break;
case 4:
System.out.print("Enter student index to display: ");
index = scanner.nextInt();
sms.displayStudent(index);
break;
case 5:
exit = true;
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
scanner.close();
}
}
class Student {
private String name;
private int age;
private int grade;
public Student(String name, int age, int grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
public String toString() {
return "Name: " + name + "\nAge: " + age + "\nGrade: " + grade;
}
}
```
该示例代码实现了一个简单的学生管理系统,可以添加、删除、显示所有学生和显示单个学生。它使用了一个 `Student` 类来表示学生,`StudentManagementSystem` 类来管理学生,以及一个主方法来处理用户输入和调用相应的方法。
阅读全文