gpt4 book ai didi

java - 为什么此代码中会出现 "No line found"异常?

转载 作者:行者123 更新时间:2023-12-01 18:15:50 26 4
gpt4 key购买 nike

以下方法会导致未找到行异常:

private static String getRebaseAnswer(boolean isFirst, boolean isLast) {
System.out.println("Would you like to (c)ontinue, (s)kip this commit, or"
+ " change this commit's (m)essage?");
Scanner in = new Scanner(System.in);
String answer;
while (true) {
answer = in.nextLine(); // <--- This Line
if (answer.equals("c") || answer.equals("m")) {
in.close();
return answer;
} else if (answer.equals("s") && !isFirst && !isLast) {
in.close();
return answer;
} else {
System.out.println("Would you like to (c)ontinue, (s)kip this commit, or"
+ " change this commit's (m)essage?");
}
}
}

我正在这个方法中调用该方法:

...
String answer;
Scanner in;
currHead = branchHeads.get(arg);
while (toRebase != null) {
System.out.println("Currently replaying:");
toRebase.getNode().printInfo();
answer = getRebaseAnswer(isFirst, toRebase.getParent() == null); // <--- This Line
...

是什么导致了这个错误?扫描仪不应该等待我输入一行然后再继续 getRebaseAnswer 方法吗?我的代码中的另一个方法与上述方法具有完全相同的结构,并且没有遇到任何问题。我已经检查了有关此问题的多个其他帖子,但他们的建议都与此问题无关或无法解决它。

此方法运行没有问题:

private static boolean handleDangerous() {
System.out.println("Warning: The command you entered may alter the files in your"
+ " working directory. Uncommitted changes may be lost. Are you sure you"
+ " want to continue? (yes/no)");
Scanner in = new Scanner(System.in);
String answer;
while (true) {
answer = in.nextLine();
if (answer.equals("yes")) {
in.close();
return true;
} else if (answer.equals("no")) {
in.close();
return false;
} else {
System.out.println("Not a valid answer, please enter (yes/no).");
}
}
}

最佳答案

当您创建连接到 System.in 的扫描仪并将其关闭时,您也会关闭 System.in。因此,后续尝试从 System.in 读取数据将导致您观察到的异常。

避免这种情况的方法是只创建一次扫描仪,并且在程序完成之前永远不要关闭它。应将此扫描程序传递给需要从 System.in 读取的任何函数。

关于java - 为什么此代码中会出现 "No line found"异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29622273/

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