以下是一个简单的学生管理系统的Java代码示例:
import java.util.ArrayList;
class Student {
private String name;
private int age;
private String address;
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
}
class StudentManagementSystem {
private ArrayList<Student> studentList;
public StudentManagementSystem() {
studentList = new ArrayList<Student>();
}
public void addStudent(Student student) {
studentList.add(student);
}
public void deleteStudent(String name) {
for (Student student : studentList) {
if (student.getName().equals(name)) {
studentList.remove(student);
break;
}
}
}
public Student searchStudent(String name) {
for (Student student : studentList) {
if (student.getName().equals(name)) {
return student;
}
}
return null;
}
public void displayAllStudents() {
for (Student student : studentList) {
System.out.println("Name: " + student.getName());
System.out.println("Age: " + student.getAge());
System.out.println("Address: " + student.getAddress());
System.out.println();
}
}
}
public class Main {
public static void main(String[] args) {
// 创建学生管理系统对象
StudentManagementSystem sms = new StudentManagementSystem();
// 添加学生
Student s1 = new Student("Tom", 18, "New York");
sms.addStudent(s1);
// 搜索学生
Student searchResult = sms.searchStudent("Tom");
if (searchResult != null) {
System.out.println("Student found!");
System.out.println("Name: " + searchResult.getName());
System.out.println("Age: " + searchResult.getAge());
System.out.println("Address: " + searchResult.getAddress());
} else {
System.out.println("Student not found.");
}
// 显示所有学生
sms.displayAllStudents();
// 删除学生
sms.deleteStudent("Tom");
}
}
使用示例:
// 创建学生管理系统对象
StudentManagementSystem sms = new StudentManagementSystem();
// 添加学生
Student s1 = new Student("Tom", 18, "New York");
sms.addStudent(s1);
// 搜索学生
Student searchResult = sms.searchStudent("Tom");
if (searchResult != null) {
System.out.println("Student found!");
System.out.println("Name: " + searchResult.getName());
System.out.println("Age: " + searchResult.getAge());
System.out.println("Address: " + searchResult.getAddress());
} else {
System.out.println("Student not found.");
}
// 显示所有学生
sms.displayAllStudents();
// 删除学生
sms.deleteStudent("Tom");