我创建了一个算法来读取文件并检查用户输入的多个问题。我正在使用Netbeans,它建议尝试使用资源。我不确定的是关闭文件。当我第一次创造了我的算法,我把file.close()在错误的地方,因为它无法达到的,因为有之前“返回”声明:用试用资源环绕扫描仪
while (inputFile.hasNext()) {
String word = inputFile.nextLine();
for (int i = 0; i < sentance.length; i++) {
for (int j = 0; j < punc.length; j++) {
if (sentance[i].equalsIgnoreCase(word + punc[j])) {
return "I am a newborn. Not even a year old yet.";
}
}
}
}
inputFile.close(); // Problem
所以我固定它这样的:
File file = new File("src/res/AgeQs.dat");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()) {
String word = inputFile.nextLine();
for (int i = 0; i < sentance.length; i++) {
for (int j = 0; j < punc.length; j++) {
if (sentance[i].equalsIgnoreCase(word + punc[j])) {
inputFile.close(); // Problem fixed
return "I am a newborn. Not even a year old yet.";
}
}
}
}
是,当我将它设置了错误的方式,Netbeans的建议这个问题:
File file = new File("src/res/AgeQs.dat");
try (Scanner inputFile = new Scanner(file)) {
while (inputFile.hasNext()) {
String word = inputFile.nextLine();
for (int i = 0; i < sentance.length; i++) {
for (int j = 0; j < punc.length; j++) {
if (sentance[i].equalsIgnoreCase(word + punc[j])) {
return "I am a newborn. Not even a year old yet.";
}
}
}
}
}
是Netbeans的纠正我的代码,或只是删除文件的结束?这是一个更好的方式去做这件事吗?除非我确切知道发生了什么,否则我不喜欢使用代码。
让问题更广泛 - 他们会将它关闭太宽,使其具体 - 太近了。 – Stepan