我被这个错误困扰了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课堂上,对此真的感到很困惑,而且我觉得即使问了问题,他们也没有足够地解释这一过程。谁能解释一下?谢谢。

最佳答案

首先,您需要在以下行中更改“修复”:

String answer = user.next();

阅读:

String answer = user.nextLine();

这意味着您将捕获换行符,这意味着直到下一个Scanner调用之前,该换行符才会被缓冲(防止您读取文件路径提示)。

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

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

10-07 19:10
查看更多