要使用ArrayList來實現學生管理系統,首先需要定義一個Student類來表示學生對象。每個學生對象可以有學號、姓名、性別、年齡等屬性。
然后,在學生管理系統中可以進行如下操作:
下面是一個簡單的示例代碼:
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);
System.out.println("添加學生成功!");
}
public void deleteStudent(String studentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getStudentId().equals(studentId)) {
students.remove(i);
System.out.println("刪除學生成功!");
return;
}
}
System.out.println("找不到指定學生!");
}
public void updateStudent(String studentId, Student newStudent) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getStudentId().equals(studentId)) {
students.set(i, newStudent);
System.out.println("更新學生信息成功!");
return;
}
}
System.out.println("找不到指定學生!");
}
public void queryStudent(String studentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getStudentId().equals(studentId)) {
System.out.println("學生信息如下:");
System.out.println(students.get(i));
return;
}
}
System.out.println("找不到指定學生!");
}
public void displayAllStudents() {
System.out.println("所有學生信息如下:");
for (Student student : students) {
System.out.println(student);
}
}
public static void main(String[] args) {
StudentManagementSystem system = new StudentManagementSystem();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("請選擇操作:");
System.out.println("1. 添加學生");
System.out.println("2. 刪除學生");
System.out.println("3. 修改學生信息");
System.out.println("4. 查詢學生信息");
System.out.println("5. 顯示所有學生信息");
System.out.println("0. 退出");
int choice = scanner.nextInt();
scanner.nextLine(); // 讀取換行符
switch (choice) {
case 1:
System.out.println("請輸入學生學號:");
String studentId = scanner.nextLine();
System.out.println("請輸入學生姓名:");
String name = scanner.nextLine();
System.out.println("請輸入學生性別:");
String gender = scanner.nextLine();
System.out.println("請輸入學生年齡:");
int age = scanner.nextInt();
scanner.nextLine(); // 讀取換行符
Student newStudent = new Student(studentId, name, gender, age);
system.addStudent(newStudent);
break;
case 2:
System.out.println("請輸入要刪除的學生學號:");
String deleteStudentId = scanner.nextLine();
system.deleteStudent(deleteStudentId);
break;
case 3:
System.out.println("請輸入要修改的學生學號:");
String updateStudentId = scanner.nextLine();
System.out.println("請輸入新的學生姓名:");
String newName = scanner.nextLine();
System.out.println("請輸入新的學生性別:");
String newGender = scanner.nextLine();
System.out.println("請輸入新的學生年齡:");
int newAge = scanner.nextInt();
scanner.nextLine(); // 讀取換行符
Student updatedStudent = new Student(updateStudentId, newName, newGender, newAge);
system.updateStudent(updateStudentId, updatedStudent);
break;
case 4:
System.out.println("請輸入要查詢的學生學號:");
String queryStudentId = scanner.nextLine();
system.queryStudent(queryStudentId);
break;
case 5:
system.displayAllStudents();
break;
case 0