Java: FileNotFoundException 完全结束

Java: FileNotFoundException ends completely

我被这个错误困扰了 3 个小时,这是因为在我的 CSE 课程中我们刚刚学会了在方法中输入 "throws FileNotFoundException" 但是在我的代码中:

public static void main(String[] args) throws FileNotFoundException {
  Scanner user = new Scanner(System.in);
  intro();
  prompt(user);
  }
public static void prompt(Scanner user) throws FileNotFoundException {
  boolean game = true;
  while(game != false) {
     System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
     String answer = user.next();
     answer = answer.toUpperCase();      
     if(answer.equals("C")) {
        create(user);
     } else if(response == "V") {
        view(user);
     } else if(answer.equals("Q")) {
           game = false;
     }
  }
}
  public static void create(Scanner user) throws FileNotFoundException {
  System.out.print("Input file name: ");
  String fileName = user.nextLine();
  Scanner file = new Scanner(new File(fileName));
  File f = new File(fileName);
  if(!f.exists()) {
     System.out.print("File not found. Try again: ");
     fileName = user.nextLine();
     f = new File(fileName);
  }
  System.out.print("Output file name: ");
  PrintStream ot = new PrintStream(new File(user.nextLine()));
  filing(user, fileName, ot);
}

当运行通过,并在C中输入:是这样的。

Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story
The result will be written to an output file

(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: Exception in thread "main" java.io.FileNotFoundException:  (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)
    at java.util.Scanner.<init>(Scanner.java:656)
    at MadLibs.create(MadLibs.java:47)
    at MadLibs.prompt(MadLibs.java:35)
    at MadLibs.main(MadLibs.java:16)

在我的 CSE class 中对此感到非常困惑,我觉得即使在提问之后他们也没有充分解释这个过程。谁能解释一下?谢谢

首先,您需要更改 "fix" 以下行:

String answer = user.next();

阅读:

String answer = user.nextLine();

这意味着您将捕获换行符,这意味着在下一次扫描程序调用之前不会对其进行缓冲(防止您读取文件路径提示)。

然后这里也有一些修复。无需创建新的扫描仪,您已经拥有一个可以使用的扫描仪:

System.out.print("Input file name: ");
String fileName = user.nextLine();
File f = new File(fileName);
if(!f.exists()) {

由于您首先使用 user.next() 来获取用户输入,所以扫描仪只会读取下一个字符,而不是换行符。

稍后在您的代码中执行以下操作:

System.out.print("Input file name: ");
String fileName = user.nextLine();

user.nextLine() 调用只是读取 user.next() 调用留下的换行符。

解决此问题的一种方法是读取 nextLine 但忽略输入,如下所示:

user.nextLine();
System.out.print("Input file name: ");
String fileName = user.nextLine();

现在,当提示输入文件名时,它将正常工作。