一个文件名为1.txt,里面有学生学号、姓名、成绩,写一个Java代码,用list读取该文件,通过输入该学生学号实现删去该学生信息
时间: 2024-04-15 22:26:07 浏览: 69
好的,以下是一个示例的Java代码,可以实现你的需求:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Student {
private String studentId;
private String name;
private double score;
public Student(String studentId, String name, double score) {
this.studentId = studentId;
this.name = name;
this.score = score;
}
public String getStudentId() {
return studentId;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
}
public class Main {
public static void main(String[] args) {
List<Student> students = readStudentData("1.txt");
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要删除的学生学号:");
String inputStudentId = scanner.nextLine();
boolean found = false;
for (int i = 0; i < students.size(); i++) {
Student student = students.get(i);
if (student.getStudentId().equals(inputStudentId)) {
students.remove(i);
found = true;
break;
}
}
if (found) {
System.out.println("成功删除学生信息。");
saveStudentData(students, "1.txt");
} else {
System.out.println("找不到该学生信息。");
}
}
public static List<Student> readStudentData(String filename) {
List<Student> students = new ArrayList<>();
try {
File file = new File(filename);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(",");
if (parts.length == 3) {
String studentId = parts[0].trim();
String name = parts[1].trim();
double score = Double.parseDouble(parts[2].trim());
Student student = new Student(studentId, name, score);
students.add(student);
}
}
scanner.close();
} catch (IOException e) {
System.out.println("文件读取错误:" + e.getMessage());
}
return students;
}
public static void saveStudentData(List<Student> students, String filename) {
try {
FileWriter writer = new FileWriter(filename);
for (Student student : students) {
writer.write(student.getStudentId() + "," + student.getName() + "," + student.getScore() + "\n");
}
writer.close();
} catch (IOException e) {
System.out.println("文件保存错误:" + e.getMessage());
}
}
}
```
请确保将文件 `1.txt` 放在与代码相同的目录下,文件内容格式如下:
```
学号1,姓名1,成绩1
学号2,姓名2,成绩2
学号3,姓名3,成绩3
...
```
注意:这只是一个简单的示例,没有对输入进行严格的错误处理。在实际应用中,你可能需要增加更多的错误处理和异常处理机制。此外,删除信息后会将修改后的数据保存回原文件。
阅读全文