Or Nevo
Or Nevo

Reputation: 183

java.util.NoSuchElementException: No line found - Reading user input works only once

I tried to create a very simple program (it doesn't matters, but a Minesweeper game), and I had the following problem: When I try to get the user input (with Scanner), it works the first time (on the first turn), but at the second turn, after pressing enter, it throws the following exception: java.util.NoSuchElementException: No line found.

Nothing has changed between the two turns, and I create a new Scanner instance on every turn.

The code:

public String nextTurn() {
    Scanner scn = new Scanner(System.in);

    System.out.print("Please insert your action: ");
    StringTokenizer input = new StringTokenizer(scn.nextLine());
    scn.close();
    //...
}

Again, it works when I call this method the first time, but fails on the second call. Do you have an idea what the problem might be?

Upvotes: 2

Views: 1273

Answers (1)

RealSkeptic
RealSkeptic

Reputation: 34628

System.in is an input stream that takes in all your console input.

Just like any input stream, it can be closed. The user can close it (by pressing ctrlD or ctrlZ), but you can also close it programmatically - it is a Closeable object.

When you have a scanner based on an input stream, and you close the scanner, it automatically also closes the input stream that lies behind it. That is, by the first time that you close scn, you have closed System.in.

The next time you create a scanner on System.in, it is basically a scanner on a closed stream. When you try to call any of the nextXXX methods, it will tell you that there is no such element in the stream. That is because the stream has already been closed.

What you should do is open the scanner just once, in the beginning of your program, and close it just once - at the end of your program. You can keep using the same scanner - there is actually no need to open more than one scanner for the same input stream.

Upvotes: 5

Related Questions