我一直在练习扫描仪和异常,它们相当新,所以也许我在这里遗漏了一些东西:
这是编译器表示无法找到文件名或 f 的第一种方式。
do {
try {
System.out.print("Enter the file name: ");
String filename = k.nextLine();
Scanner f = new Scanner(new File(filename));
done = true;
}
catch(FileNotFoundException ex1){
System.out.println("The file "+filename+" does not exist.");
}
catch(Exception e){
System.out.println("Unpredicted exception");
}
} while (!done);
我以为我应该把它放在外面来修复它,但是另一种方式它提示 f 和文件名可能尚未初始化
Scanner k = new Scanner(System.in), f;
String filename;
boolean done = false;
// Request file from the user
do {
try {
System.out.print("Enter the file name: ");
filename = k.nextLine();
f = new Scanner(new File(filename));
done = true;
}
catch(FileNotFoundException ex1){
System.out.println("The file "+filename+" does not exist.");
}
catch(Exception e){
System.out.println("Unpredicted exception");
}
} while (!done);
最佳答案
将文件名的值初始化为空。这样,如果输入了 catch block ,当您打印错误消息时,它仍然具有可使用的值。
String filename = null;
关于java - 这样做的正确方法是什么?初始化/符号未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23259005/