Java NoTouchElementException:在文本文件中读取时未找到行
我目前正在制作一个文本冒险游戏,在尝试读取包含房间描述的文本文件时遇到了一个问题。每当我运行程序时,我都可以正确地读入并分配第一个文本文件,但第二个文本文件会抛出以下错误Java NoTouchElementException:在文本文件中读取时未找到行,java,text-files,java.util.scanner,Java,Text Files,Java.util.scanner,我目前正在制作一个文本冒险游戏,在尝试读取包含房间描述的文本文件时遇到了一个问题。每当我运行程序时,我都可以正确地读入并分配第一个文本文件,但第二个文本文件会抛出以下错误 Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1540) at Input.getInput(Input.java:9)
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
方法时都关闭std输入<代码>扫描仪::关闭关闭基础流
在外部创建扫描仪
,并继续使用它。在上次调用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;
}
那么,您在哪里提供读取数据的文件名?我们可以看到什么是
输入以及它是如何创建的吗?@Tdorno:是的。我还想知道关于Input
。Edit:将其编辑到OP中。那么将输入数据输入到buildRoom方法中呢?你检查过了吗?