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



以下方法会导致No line found Exception

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读取的任何函数。

不要

关闭扫描仪,否则流也会关闭。

in.close();

从当前位置删除此行并将其放在最后的 Main 方法中,以便在所有操作流之后关闭。.

您可能正在调用

已经关闭流的其他方法,然后您正在调用此方法。

相关内容

最新更新