使用ArrayList集合管理班级的花名册,对于花名册的管理包括名字的添加、查找、删除、修改等基本功能
时间: 2023-07-04 07:22:58 浏览: 136
好的,针对你的问题,我可以给出以下代码示例:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class StudentManager {
private ArrayList<String> nameList;
public StudentManager() {
nameList = new ArrayList<>();
}
public void addStudent(String name) {
nameList.add(name);
System.out.println(name + "已成功添加到花名册中!");
}
public void searchStudent(String name) {
int index = nameList.indexOf(name);
if (index != -1) {
System.out.println(name + "在花名册中的位置为:" + (index + 1));
} else {
System.out.println(name + "不在花名册中!");
}
}
public void deleteStudent(String name) {
boolean result = nameList.remove(name);
if (result) {
System.out.println(name + "已成功从花名册中删除!");
} else {
System.out.println(name + "不在花名册中,无法删除!");
}
}
public void modifyStudent(String oldName, String newName) {
int index = nameList.indexOf(oldName);
if (index != -1) {
nameList.set(index, newName);
System.out.println(oldName + "已成功修改为" + newName + "!");
} else {
System.out.println(oldName + "不在花名册中,无法修改!");
}
}
public void displayAllStudents() {
if (nameList.size() == 0) {
System.out.println("花名册中没有学生!");
} else {
System.out.println("花名册中的学生有:");
for (int i = 0; i < nameList.size(); i++) {
System.out.println((i + 1) + "、" + nameList.get(i));
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StudentManager manager = new StudentManager();
while (true) {
System.out.println("请选择要进行的操作:");
System.out.println("1.添加学生\t2.查找学生\t3.删除学生\t4.修改学生\t5.显示所有学生\t6.退出");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("请输入要添加的学生姓名:");
String addName = scanner.next();
manager.addStudent(addName);
break;
case 2:
System.out.println("请输入要查找的学生姓名:");
String searchName = scanner.next();
manager.searchStudent(searchName);
break;
case 3:
System.out.println("请输入要删除的学生姓名:");
String deleteName = scanner.next();
manager.deleteStudent(deleteName);
break;
case 4:
System.out.println("请输入要修改的学生姓名和新姓名(用空格分隔):");
String oldName = scanner.next();
String newName = scanner.next();
manager.modifyStudent(oldName, newName);
break;
case 5:
manager.displayAllStudents();
break;
case 6:
System.out.println("谢谢使用!");
System.exit(0);
default:
System.out.println("输入有误,请重新选择!");
break;
}
}
}
}
```
这段代码实现了使用ArrayList集合管理班级的花名册,包括名字的添加、查找、删除、修改等基本功能。你可以根据自己的需要进行修改和扩展,希望对你有所帮助。
阅读全文