gpt4 book ai didi

Java:FileNotFoundException完全结束

转载 作者:行者123 更新时间:2023-11-30 03:25:52 25 4
gpt4 key购买 nike

我已经被这个错误困扰了 3 个小时,这是因为在我的 CSE 类(class)中,我们刚刚学会了在方法中添加“抛出 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)中对此感到非常困惑,而且我觉得即使在提出问题后他们也没有充分解释该过程。谁能解释一下吗?谢谢。

最佳答案

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

字符串答案 = user.next();

阅读:

字符串答案 = user.nextLine();

这意味着您将捕获换行符,这意味着它不会被缓冲,直到下一次扫描程序调用(防止您读取文件路径提示)。

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

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

关于Java:FileNotFoundException完全结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30250721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com