编程题: 已知有一个文件student.txt保存班级的学生名单。每个学生的记录占据一行,形如: 6009125088,张三 6009125090,李四 …… 请编写程序,实现简单学生记录检索应用。即从键盘输入一个学生的学号,如果学号在在student.txt文件中,可以显示该学生记录,如果输入的学号不在文件中,则显示检索失败的信息。其中,代码必须结合异常处理机制来实现,例如自定义一个StudentNotFoundException用于表示学生检索失败的异常。
时间: 2024-03-30 22:35:07 浏览: 42
下面是一个Java实现的例子:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class StudentSearch {
public static void main(String[] args) {
BufferedReader reader = null;
try {
// 读取student.txt文件
reader = new BufferedReader(new FileReader("student.txt"));
String line;
boolean found = false;
// 从键盘读取学号
System.out.print("请输入学生学号:");
String id = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
// 在文件中查找学生记录
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
if (parts[0].equals(id)) {
System.out.println("找到学生:" + parts[1]);
found = true;
break;
}
}
// 如果没有找到则抛出异常
if (!found) {
throw new StudentNotFoundException("未找到学生记录");
}
} catch (IOException e) {
System.err.println("读取文件出错:" + e.getMessage());
} catch (StudentNotFoundException e) {
System.err.println(e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.err.println("关闭文件出错:" + e.getMessage());
}
}
}
// 自定义异常类
static class StudentNotFoundException extends Exception {
public StudentNotFoundException(String message) {
super(message);
}
}
}
```
这里使用了Java的`BufferedReader`类来读取文件和从键盘输入,使用了自定义的`StudentNotFoundException`异常类来表示学生检索失败的情况。在`try`块中,首先打开文件并读取每行学生记录,然后从键盘读取学号,并在文件中查找对应的学生记录。如果找到了,则输出学生姓名并设置`found`标志为`true`,然后跳出循环;如果没有找到,则抛出`StudentNotFoundException`异常。在`catch`块中,分别处理IO异常和自定义异常,并在`finally`块中关闭文件。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)