【发布时间】:2016-04-06 20:30:17
【问题描述】:
我正在制作一个刽子手游戏,最近实现了一个文件读取方法来随机化单词;但是,在随机读取文件读取器的哪一行之前,我测试文件阅读器并没有走得太远,而且我的代码似乎跳过了 try catch 块? 以下是使用此方法的构造函数中的一行:
word = determineWord();
方法如下:
String determineWord() {
String fileName = "HangmanWords.txt";
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
line = bufferedReader.readLine();
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Can't open file");
}
catch(IOException ex) {
System.out.println("Error reading file");
}
return line;
}
我收到的错误是 NullPointerException,我相信是因为 line 最初设置为 null,并且 word 在我的程序中不能为 null。
【问题讨论】:
-
它不会跳过 try-catch 块。但是您在每次迭代时读取两行,并且返回 line 的最终值,该值始终为 null,因为当 line 为 null 时循环停止。不确定您要做什么。
-
@JBNizet while 循环检查并查看是否还有另一行要读取。行应作为文件的最后一行返回。
标签: java