一个文件名为1.txt,里面有学号、姓名、成绩,写一个Java代码,用list读取该文件,然后使得界面,通过输入学号可以,出现该学生姓名、成绩
时间: 2024-04-14 19:26:53 浏览: 89
学生成绩.java
好的,以下是一个示例的Java代码,可以实现你的需求:
```java
import java.io.File;
import java.io.FileNotFoundException;
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();
for (Student student : students) {
if (student.getStudentId().equals(inputStudentId)) {
System.out.println("姓名:" + student.getName());
System.out.println("成绩:" + student.getScore());
return;
}
}
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 (FileNotFoundException e) {
System.out.println("文件 " + filename + " 不存在。");
}
return students;
}
}
```
请确保将文件 `1.txt` 放在与代码相同的目录下,文件内容格式如下:
```
学号1,姓名1,成绩1
学号2,姓名2,成绩2
学号3,姓名3,成绩3
...
```
注意:这只是一个简单的示例,没有对输入进行严格的错误处理。在实际应用中,你可能需要增加更多的错误处理和异常处理机制。
阅读全文