Java扫描器hasNext()不会返回false [英] Java Scanner hasNext() doesn't return false

查看:61
本文介绍了Java扫描器hasNext()不会返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从用户连续读取输入,直到用户键入退出为止.我只是通过输入"quit"来测试它,但是console.hasNext()似乎没有返回false.实际上,似乎该程序在第7行(hasNext()行)上被阻止.有什么想法吗?

I am trying to read input continuously from the user until the user types quit. I am testing it by just typing 'quit' but console.hasNext() doesn't seem to be returning false. In fact it seems that the program is blocked on line 7(hasNext() line). Any ideas?

    boolean bool = true;
    while (bool) {
        System.out.println("Type 'quit':");
        Scanner console = new Scanner(System.in);
        if (console.next().equals("quit")) {
            System.out.println("You typed quit");
            System.out.println("check: " + console.hasNext()); // This line doesnt print
            bool = false;
        }
    }

推荐答案

如果将Scanner声明为System.in,它将询问System.in是否要接收下一个值.然后,in类将等待用户输入某些内容,然后返回true.

If your Scanner is declared as System.in, it will be asking System.in if there is a next value to be received. The in class will then wait for the user to input something, then return true.

为文件之类的内容保留hasNext(),其中输入大小是固定的.这样,当Scanner查询文件时,它就有一个确定的hasNext().

Reserve hasNext() for things like files, where the input size is fixed. That way, when Scanner queries the file, it has a definite hasNext().

相反,我建议使用字符串作为下一个值,然后检查它是否与整数格式匹配.如果是这样,则将其转换,否则,请根据需要进行处理.

Instead, I suggest grabbing the next value as a String, then checking if it matches the integer format. If it does, then convert it, otherwise, handle it however you'd like.

这篇关于Java扫描器hasNext()不会返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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