hasNext() - 什么时候阻止,为什么? [英] hasNext() - when does it block and why?

查看:159
本文介绍了hasNext() - 什么时候阻止,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 Scanner 对象读取命令。为了检查输入语法,我使用 sc.hasNext()(对于缺少命令的情况)。它已经在很多情况下都能正常工作,但是我现在已经在JavaAPI中描述为可以阻塞并等待输入的情况。

I'm trying to read commands via a Scanner Object. For checking the Input Syntax I use sc.hasNext() (for the case of missing commands). It did work fine for many cases already, but now I have the case that's described in the JavaAPI as "MAY block and wait for Input".

什么时候 hasNext()方法块,我该如何控制它?有趣的事情是它在块之前的3个案例中完美地工作。此外,JavaAPI描述 hasNext()作为检查是否有另一个输入的正确方法,以便方法 next()不会产生异常

When does the hasNext() method block and how can I control it? The funny Thing is that it work's perfectly fine with 3 cases before the block. Also the JavaAPI describes hasNext() as the proper method for checking wether there is another Input or not so that the Method next() doesn't produce an Exception.

这是我到目前为止所生产的代码:

Here is the code I did produce till now:

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,但这不应该是一个问题 - 至少到目前为止它还没有。

Thanks in advance, I couldn't find anything on this Topic an my own. The Scanner is defined as a System.in, but that shouldn't be a Problem - at least it hasn't been one till now.

推荐答案

通过Console或TextFile进行测试之间存在差异。如果我从Console读取,程序需要一个Stream,它将等待进一步的输入。

There is a difference between testing via Console or via TextFile. If I read from Console the program expects a Stream and it will wait for further Input.

通过Textfile的输入进行测试时(仍然使用System.in进行扫描,使用Java程序)hasNext()将在文件末尾返回false,因为无法再进行输入。

When testing via Input from Textfile (still with System.in for the Scanner, using Java Program ) the hasNext() will return false at the end of the file as no further Input can be done.

我无法找到文档(在 https://docs.oracle.com/ javase / 9 / docs / api / java / util / Scanner.html#hasNext-- )在这个主题上。因此,如果有人找到正确和技术正确的答案,我会非常感激。

I can't really find documentation (in https://docs.oracle.com/javase/9/docs/api/java/util/Scanner.html#hasNext--) on this Topic. So if anyone finds a proper and technical correct answer I would be very greatfull.

这篇关于hasNext() - 什么时候阻止,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆