java使用数组完成学生姓名的增删改查
时间: 2023-03-19 14:21:59 浏览: 81
下面是使用Java数组完成学生姓名的增删改查的示例代码:
```java
import java.util.Scanner;
public class StudentManagementSystem {
private static String[] students = new String[100]; // 保存学生姓名的数组
private static int numStudents = 0; // 学生数量
public static void main(String[] args) {
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. 退出程序");
int choice = scanner.nextInt();
switch (choice) {
case 1:
addStudent(scanner);
break;
case 2:
deleteStudent(scanner);
break;
case 3:
modifyStudent(scanner);
break;
case 4:
queryStudent(scanner);
break;
case 5:
System.exit(0);
default:
System.out.println("无效的选项,请重新输入!");
break;
}
}
}
// 添加学生姓名
private static void addStudent(Scanner scanner) {
if (numStudents >= students.length) {
System.out.println("添加失败,学生数量已达到最大值!");
return;
}
System.out.println("请输入要添加的学生姓名:");
String name = scanner.next();
students[numStudents++] = name;
System.out.println("添加成功!");
}
// 删除学生姓名
private static void deleteStudent(Scanner scanner) {
System.out.println("请输入要删除的学生姓名:");
String name = scanner.next();
int index = findStudent(name);
if (index == -1) {
System.out.println("删除失败,未找到指定学生姓名!");
return;
}
for (int i = index; i < numStudents - 1; i++) {
students[i] = students[i + 1];
}
numStudents--;
System.out.println("删除成功!");
}
// 修改学生姓名
private static void modifyStudent(Scanner scanner) {
System.out.println("请输入要修改的学生姓名:");
String oldName = scanner.next();
int index = findStudent(oldName);
if (index == -1) {
System.out.println("修改失败,未找到指定学生姓名!");
return;
}
System.out.println("请输入新的学生姓名:");
String newName = scanner.next();
students[index] = newName;
System.out.println("修改成功!");
}
// 查询学生姓名
private static void queryStudent(Scanner scanner) {
System.out.println("请输入要查询的学生姓名:");
String name = scanner.next();
int index = findStudent(name);
if (index == -1) {
System.out.println("查询失败,未找到指定学生姓名!");
return;
}
System.out.println("查询结果:");
System.out.println(students[index]);
}
// 查找学生姓名
private static int findStudent(String name) {
for (int i = 0; i < numStudents; i++) {
if (students[i].equals(name)) {
return i;
}
}
return -1;
}
}
```
在上面的代码
阅读全文