用java中集合的方法实现创建学生类(学号,姓名),键盘输入N个学生信息,将学生信息保存到List中 要求: 1.写一个方法,完成按照学号升序显示学生信息 2.写一个方法,根据学号修改学生姓名3.将输入的N个学生信息保存到文件中,在从文件中查询所有学生信息输出在控制台上
时间: 2024-04-21 21:27:30 浏览: 61
好的,以下是实现您需求的Java代码示例:
```java
import java.io.*;
import java.util.*;
class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.print("请输入学生数量: ");
int n = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < n; i++) {
System.out.print("请输入学生学号: ");
int id = scanner.nextInt();
scanner.nextLine();
System.out.print("请输入学生姓名: ");
String name = scanner.nextLine();
Student student = new Student(id, name);
studentList.add(student);
}
showStudentInfoAsc(studentList);
modifyStudentNameById(studentList);
saveStudentInfoToFile(studentList);
readStudentInfoFromFile();
}
public static void showStudentInfoAsc(List<Student> studentList) {
Collections.sort(studentList, Comparator.comparingInt(Student::getId));
System.out.println("按学号升序显示学生信息:");
for (Student student : studentList) {
System.out.println("学号:" + student.getId() + ",姓名:" + student.getName());
}
}
public static void modifyStudentNameById(List<Student> studentList) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要修改的学生学号: ");
int id = scanner.nextInt();
scanner.nextLine();
for (Student student : studentList) {
if (student.getId() == id) {
System.out.print("请输入新的学生姓名: ");
String name = scanner.nextLine();
studentList.remove(student);
student.setName(name);
studentList.add(student);
System.out.println("学生信息修改成功!");
return;
}
}
System.out.println("未找到该学生学号!");
}
public static void saveStudentInfoToFile(List<Student> studentList) {
try {
FileWriter writer = new FileWriter("student_info.txt");
for (Student student : studentList) {
writer.write(student.getId() + "," + student.getName() + "\n");
}
writer.close();
System.out.println("学生信息保存成功!");
} catch (IOException e) {
System.out.println("保存学生信息失败:" + e.getMessage());
}
}
public static void readStudentInfoFromFile() {
try {
FileReader reader = new FileReader("student_info.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
System.out.println("从文件中查询所有学生信息:");
while ((line = bufferedReader.readLine()) != null) {
String[] info = line.split(",");
int id = Integer.parseInt(info[0]);
String name = info[1];
System.out.println("学号:" + id + ",姓名:" + name);
}
bufferedReader.close();
} catch (IOException e) {
System.out.println("读取学生信息失败:" + e.getMessage());
}
}
}
```
这段代码实现了以下功能:
1. 根据输入的学生数量,从键盘读取学生的学号和姓名,并将学生信息保存到List中。
2. 按照学号升序显示学生信息。
3. 根据输入的学号修改学生的姓名。
4. 将学生信息保存到文件中,并从文件中读取并输出所有学生信息到控制台。
请注意,代码中会提示您输入学生数量、学号、姓名等信息。根据具体需求,您可以根据这个示例进行修改和扩展。
阅读全文