NoSuchElementException:在读取文本文件时找不到行

NoSuchElementException: No Line Found, while reading in text file

我目前正在开发一款文字冒险游戏,但我 运行 在尝试读取包含房间描述的文本文件时遇到了问题。每当我 运行 程序时,我都可以正确读入并分配第一个文本文件,但第二个会抛出以下错误...

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1540)
    at Input.getInput(Input.java:9)
    at Room.buildRoom(Room.java:92)
    at Main.main(Main.java:19)

我完全不确定是什么原因造成的。我试过四处移动东西,但无济于事。下面是我在房间对象本身上调用以将所有信息分配给它的函数。

public void buildRoom(int num, String name, Room north,
        Room south, Room east, Room west) throws FileNotFoundException {
    System.out
            .println("Please input the location of the file you'd like to read in. Please note that you must read in the files in numerical order, or your game will not work.");

    String input = Input.getInput();

    File file = new File(input);
    Scanner reader = new Scanner(file);

    String description = reader.next();
    this.setDescription(description);

    this.setNorthExit(north);
    this.setSouthExit(south);
    this.setEastExit(east);
    this.setWestExit(west);
    reader.close();
}

如果您能帮助我们找出发生这种情况的原因,我们将不胜感激。如果您有任何问题,请随时提出,我会尽我所能回答。

编辑:输入函数如下...

public static String getInput() {

    System.out.print("> ");
    Scanner in = new Scanner(System.in);
    String input = in.nextLine();
    input.toLowerCase();
    in.close();
    return input;
}

不要在每次调用 getInput 方法时都关闭标准输入。 Scanner::close 关闭底层流。

在外面创建 Scanner 并继续使用它。在您最后一次调用 getInput.

之前的某个地方创建它

Scanner 对象传递给 getInput 方法。

Scanner sc = new Scanner(System.in);
while(whatever)
{
     String s = getInput(sc);
     ....

}
sc.close();

public static String getInput(Scanner in) 
{
    System.out.print("> ");
    String input = in.nextLine();
    input.toLowerCase();
    return input;
}