[英]java.util.Scanner: wait for input
I use java.util.Scanner
to read the commands from the console. 我使用
java.util.Scanner
从控制台读取命令。
try
{
ICommand cmd = cmdReader.ReadCommand();
cmd.Execute(conn);
}
catch(MyException ex)
{
// print a message about unknown command
continue;
}
Where ReadCommand
is implemented as follows: ReadCommand
的实现如下:
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;
但其他迭代返回
null
在这里if (!scanIn.hasNextLine()) return null;
even if I write something in a console. 即使我在控制台中写东西。 Looks like
java.util.Scanner
doesn't see the input. 看起来
java.util.Scanner
没有看到输入。 Am I doing something wrong? 难道我做错了什么? And how then I can wait for the user input (don't want to use the cycle with
sleep
)? 然后如何等待用户输入(不想将周期与
sleep
一起使用)?
You should not create a new Scanner
instance each time you call ReadCommand
. 您不应每次调用
ReadCommand
时都创建一个新的Scanner
实例。 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.
关闭扫描器后,如果源实现了Closeable接口,它将关闭其输入源。
So, your System.in
stream is closed after you read the first input. 因此,在读取第一个输入后,将关闭
System.in
流。
See also Java Scanner does not wait for input 另请参见Java扫描器不等待输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.