我正在尝试在此处捕获文件名。我正在测试时先给出不正确的值。从最新的(正确的路径)到最旧的(错误的路径)给出正确的值时,我得到多行“返回前”的信息。该Sysout
语句中的循环方式。我该如何解决?
static String setFilePath(){
String filepath = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("enter the file path");
filepath = keyboard.nextLine();
System.out.println("You have entered :"+filepath);
BufferedReader b = new BufferedReader(new FileReader (filepath));
}
catch (InputMismatchException | FileNotFoundException ex) {
System.out.println("Please enter a proper FilePath");
//in.next(); // Read and discard whatever string the user has entered
ex.printStackTrace();
setFilePath();
}
keyboard.close();
System.out.println("Just before returning :"+filepath);
return filepath;
}
答案 0 :(得分:1)
您在catch
中有一个递归语句:
catch (InputMismatchException | FileNotFoundException ex) {
System.out.println("Please enter a proper FilePath");
//in.next(); // Read and discard whatever string the user has entered
ex.printStackTrace();
setFilePath(); //Right here
}
因此,一旦您最终停止了递归,堆栈上的所有调用都将解决并且所有print语句将执行。要解决此问题,您需要返回方法的结果,以便退出堆栈中的方法的结果而无需打印。
return setFilePath();
关闭System.in
也是不好的做法。一般规则是,如果您没有打开资源,则不应关闭它。