简体   繁体   中英

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 )?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM