maverik
maverik

Reputation: 5586

java.util.Scanner: wait for input

I use java.util.Scanner to read the commands from the console.

try
{
    ICommand cmd = cmdReader.ReadCommand();
    cmd.Execute(conn);
}
catch(MyException ex)
{
    // print a message about unknown command
    continue;
}

Where ReadCommand is implemented as follows:

try (Scanner scanIn = new Scanner(System.in)) 
{
    if (!scanIn.hasNextLine()) return null;

    line_ = scanIn.nextLine();

    ICommand command = parser_.ParseCommand(line_);
    return command;
}

In the first iteration code works fine, I write something invalid (not a command), the code prints a warning and continues. But other iterations return null here if (!scanIn.hasNextLine()) return null; even if I write something in a console. Looks like java.util.Scanner doesn't see the input. Am I doing something wrong? And how then I can wait for the user input (don't want to use the cycle with sleep)?

Upvotes: 1

Views: 1724

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36630

You should not create a new Scanner instance each time you call ReadCommand. Create one and reuse it while reading input.

From the documentation:

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

So, your System.in stream is closed after you read the first input.

See also Java Scanner does not wait for input

Upvotes: 5

Related Questions