以下是一個簡單的Java實現學生管理系統的代碼,使用ArrayList集合來存儲學生信息。
import java.util.ArrayList;
import java.util.Scanner;
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 class StudentManagementSystem {
private ArrayList<Student> students;
public StudentManagementSystem() {
students = new ArrayList<>();
}
public void addStudent(Student student) {
students.add(student);
}
public void removeStudent(String id) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId().equals(id)) {
students.remove(i);
break;
}
}
}
public void displayStudents() {
for (Student student : students) {
System.out.println("Name: " + student.getName());
System.out.println("Age: " + student.getAge());
System.out.println("ID: " + student.getId());
System.out.println("------------------------");
}
}
public static void main(String[] args) {
StudentManagementSystem system = new StudentManagementSystem();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("1. Add Student");
System.out.println("2. Remove Student");
System.out.println("3. Display Students");
System.out.println("4. 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 ID: ");
String id = scanner.next();
Student student = new Student(name, age, id);
system.addStudent(student);
break;
case 2:
System.out.print("Enter student ID to remove: ");
String removeId = scanner.next();
system.removeStudent(removeId);
break;
case 3:
system.displayStudents();
break;
case 4:
System.exit(0);
break;
default:
System.out.println("Invalid choice. Please try again.");
break;
}
}
}
}
這個程序中,Student
類表示學生,包含姓名、年齡和學號屬性。StudentManagementSystem
類表示學生管理系統,包含一個ArrayList集合來存儲學生信息。
在main
方法中,使用一個無限循環來接受用戶的輸入操作。用戶可以選擇添加學生、刪除學生、顯示學生列表或退出程序。根據用戶的選擇,調用StudentManagementSystem
類中的相應方法來執行相應的操作。
注意:這只是一個簡單的示例,沒有進行輸入驗證和錯誤處理。在實際使用中,可能需要添加更多的功能和邏輯來滿足實際需求。