我正在尝试通过
以下是我迄今为止编写的代码:
Scanner
对象读取命令。为了检查输入语法,我使用sc.hasNext()
(对于缺少命令的情况)。这已经适用于许多情况,但现在我遇到了JavaAPI中描述的“可能阻塞并等待输入”的情况。
hasNext()
方法何时会阻塞,我如何控制它?有趣的是,在阻塞之前,它可以完美地处理3个案例。此外,JavaAPI将hasNext()
描述为检查是否有其他输入的适当方法,以便方法next()
不会产生Exception
。以下是我迄今为止编写的代码:
if (sc.hasNext() && sc.next().equals("create")) {
if (sc.hasNextInt()) {
width = sc.nextInt();
if (width > 0) {
if (sc.hasNextInt()) {
heigth = sc.nextInt();
if (heigth > 0) {
if (sc.hasNext()) { //At this point the hasNext Statement blocks for //no reason till an Input is made.
charset = sc.next();
Image = new AsciiImage(width, heigth,charset);
} else {
ret = false;
System.out.println("INPUT MISMATCH");
}
} ...//and so on
提前感谢你,我自己找不到关于这个话题的任何信息。 编辑:扫描仪被定义为System.in,但这不应该是一个问题——至少到现在为止还没有出现过。
hasNext
应该返回什么?除了阻塞直到看到流的结尾或下一个标记,它如何知道是否会有下一个标记?如果没有可用的输入,hasNext
应该返回false
。除非一直阻塞直到看到流的结尾或下一个标记,否则它无法知道是否会有下一个标记。 - Jon SkeethasNext()
请求输入。它将会阻塞直到有输入(并返回true),或者底层流被关闭(并返回false)。 - Brian Roach