我正在开发一个功能,使用户能够检查单个学生的评估结果。我使用try和catch,但是当我运行代码时,系统直接运行到catch部分,并且文件内容为空。我不确定这个问题的原因。这是我的代码:
System.out.println('\n' + "Please enter the Student's uni that you would like to call. Type 'exit' to leave");
String studentInfo = s.nextLine();
if (studentInfo.equalsIgnoreCase("exit")) {
userSelection = "exit";
}
boolean studentFound = false;
for (int i = 0; i < students.size(); i++) {
if (studentInfo.equalsIgnoreCase(students.get(i).getStudentUI())) {
studentFound = true;
try {
File singleStudentList = new File(studentInfo + " .txt");
PrintWriter writer = new PrintWriter(singleStudentList);
System.out.println(studentUniLists.get(i));
writer.println(studentUniLists.get(students.indexOf(studentInfo)));
writer.close();
} catch (Exception e) {
System.out.println("Problem writing the file. Please make sure the path is correct");
}
}
}
感谢您的帮助!
最佳答案
我的预感是您的错误出在这两行之一:
System.out.println(studentUniLists.get(i));
writer.println(studentUniLists.get(students.indexOf(studentInfo)));
您还没有包含有关 StudentUniLists 是什么的代码,因此这里有一些猜测。
我的猜测是,students.indexOf(studentInfo) 可能会返回 -1,因此当您在 List
上执行 StudentUniLists.get(-1) 时,这将为您提供一个 IndexOutOfBoundsException
。您实际上应该只捕获IOException
,以便您可以检测此类问题
关于java - java写入txt文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41307912/