java编写学生管理系统
时间: 2023-10-17 07:19:54 浏览: 57
下面是一个简单的学生管理系统的Java代码示例:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class Student {
private String name;
private int age;
private String id;
public Student(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getId() {
return id;
}
public void printInfo() {
System.out.println("Name: " + name + " Age: " + age + " ID: " + id);
}
}
public class StudentManagementSystem {
private ArrayList<Student> students;
public StudentManagementSystem() {
students = new ArrayList<Student>();
}
public void addStudent(Student student) {
students.add(student);
}
public void removeStudent(Student student) {
students.remove(student);
}
public void printAllStudents() {
for (Student s : students) {
s.printInfo();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StudentManagementSystem sms = new StudentManagementSystem();
while (true) {
System.out.println("Enter 1 to add a student, 2 to remove a student, 3 to print all students, or 4 to exit:");
int choice = sc.nextInt();
if (choice == 1) {
System.out.println("Enter student name:");
String name = sc.next();
System.out.println("Enter student age:");
int age = sc.nextInt();
System.out.println("Enter student ID:");
String id = sc.next();
Student student = new Student(name, age, id);
sms.addStudent(student);
System.out.println("Student added.");
} else if (choice == 2) {
System.out.println("Enter student ID to remove:");
String id = sc.next();
Student studentToRemove = null;
for (Student s : sms.students) {
if (s.getId().equals(id)) {
studentToRemove = s;
break;
}
}
if (studentToRemove != null) {
sms.removeStudent(studentToRemove);
System.out.println("Student removed.");
} else {
System.out.println("Student not found.");
}
} else if (choice == 3) {
sms.printAllStudents();
} else if (choice == 4) {
break;
} else {
System.out.println("Invalid choice.");
}
}
sc.close();
}
}
```
这个程序定义了两个类:`Student` 和 `StudentManagementSystem`。`Student` 类表示一个学生,包括姓名、年龄和学号等信息,以及打印信息的方法。`StudentManagementSystem` 类表示一个学生管理系统,包括添加学生、删除学生和打印所有学生的方法,以及一个 `main` 方法来运行整个程序。
在 `main` 方法中,使用一个死循环来不断读取用户输入的选项。根据用户的选择,分别调用 `addStudent`、`removeStudent` 和 `printAllStudents` 方法来添加、删除和打印学生信息。用户可以输入 `4` 来退出循环,结束程序运行。
这只是一个简单的示例,实际的学生管理系统可能需要更多的功能和复杂的实现。
阅读全文