java使用二维数组存储学生姓名,性别,班级,电话号码等信息,并实现增删改查
时间: 2024-03-10 10:45:21 浏览: 82
好的,这是一个比较常见的Java面试题,下面是示例代码:
```java
import java.util.Scanner;
public class StudentInfo {
private String[][] students;
public StudentInfo(int rows, int cols) {
students = new String[rows][cols];
}
public void addStudent(int index, String name, String gender, String className, String phoneNumber) {
students[index][0] = name;
students[index][1] = gender;
students[index][2] = className;
students[index][3] = phoneNumber;
}
public void removeStudent(int index) {
students[index] = null;
}
public void updateStudent(int index, String name, String gender, String className, String phoneNumber) {
students[index][0] = name;
students[index][1] = gender;
students[index][2] = className;
students[index][3] = phoneNumber;
}
public String[] searchStudent(String name) {
for (int i = 0; i < students.length; i++) {
if (students[i][0].equals(name)) {
return students[i];
}
}
return null;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入学生人数:");
int rows = scanner.nextInt();
int cols = 4;
StudentInfo studentInfo = new StudentInfo(rows, cols);
for (int i = 0; i < rows; i++) {
System.out.println("请输入学生信息:姓名、性别、班级、电话号码,中间用空格分隔");
String name = scanner.next();
String gender = scanner.next();
String className = scanner.next();
String phoneNumber = scanner.next();
studentInfo.addStudent(i, name, gender, className, phoneNumber);
}
System.out.println("学生信息录入完毕");
while (true) {
System.out.println("请选择操作:1. 查询学生信息 2. 修改学生信息 3. 删除学生信息 4. 退出程序");
int option = scanner.nextInt();
switch (option) {
case 1:
System.out.println("请输入要查询的学生姓名:");
String name = scanner.next();
String[] student = studentInfo.searchStudent(name);
if (student != null) {
System.out.println("查询结果如下:");
System.out.println("姓名:" + student[0] + " 性别:" + student[1] + " 班级:" + student[2] + " 电话号码:" + student[3]);
} else {
System.out.println("没有找到该学生的信息");
}
break;
case 2:
System.out.println("请输入要修改的学生姓名:");
name = scanner.next();
student = studentInfo.searchStudent(name);
if (student != null) {
System.out.println("请输入修改后的学生信息:姓名、性别、班级、电话号码,中间用空格分隔");
String newName = scanner.next();
String newGender = scanner.next();
String newClassName = scanner.next();
String newPhoneNumber = scanner.next();
studentInfo.updateStudent(Integer.parseInt(student[0]), newName, newGender, newClassName, newPhoneNumber);
System.out.println("学生信息修改成功");
} else {
System.out.println("没有找到该学生的信息");
}
break;
case 3:
System.out.println("请输入要删除的学生姓名:");
name = scanner.next();
student = studentInfo.searchStudent(name);
if (student != null) {
studentInfo.removeStudent(Integer.parseInt(student[0]));
System.out.println("学生信息删除成功");
} else {
System.out.println("没有找到该学生的信息");
}
break;
case 4:
System.out.println("程序已退出");
System.exit(0);
break;
default:
System.out.println("无效的选项,请重新输入");
break;
}
}
}
}
```
这个程序使用二维数组存储学生信息,其中第一维表示学生的索引,第二维包含四个元素,分别是学生的姓名、性别、班级和电话号码。程序提供了增加、删除、修改和查询学生信息的功能,可以通过用户输入选择要执行的操作。
阅读全文