NoSuchElementException: No Line Found, while reading in a text file

I am currently working on making a text adventure game and I am having a problem trying to read in text files containing room descriptions. Whenever I run the program I can read and assign the first text file correctly and the second throws the following error ...

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)

      

I'm not at all sure what is causing this. I've tried moving things around to no avail. Below is the function that I call the room object itself to pass all the information to it.

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();
}

      

Any help in figuring out why this is happening would be greatly appreciated. If you have any questions, feel free to ask and I will answer as far as possible.

EDIT: The input function looks like this:

public static String getInput() {

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

      

+3


source to share


1 answer


Don't close the std input every time you call the method getInput

. Scanner::close

closes the underlying stream.

Build Scanner

outside and keep using it. Create it somewhere where it lives until the last call getInput

.



Pass an object to the Scanner

method 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;
}

      

+1


source







All Articles