简体   繁体   English

Java Scanner hasNext()不返回false

[英]Java Scanner hasNext() doesn't return false

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. 我只是输入'quit'来测试它,但是console.hasNext()似乎没有返回false。 In fact it seems that the program is blocked on line 7(hasNext() line). 事实上,似乎该程序在第7行(hasNext()行)被阻止。 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;
        }
    }

If your Scanner is declared as System.in , it will be asking System.in if there is a next value to be received. 如果您的Scanner被声明为System.in ,它将询问System.in是否有接收的下一个值。 The in class will then wait for the user to input something, then return true. 然后in类中将等待用户输入内容,然后返回true。

Reserve hasNext() for things like files, where the input size is fixed. 为文件之类的东西保留hasNext() ,其中输入大小是固定的。 That way, when Scanner queries the file, it has a definite hasNext() . 这样,当Scanner查询文件时,它有一个明确的hasNext()

Instead, I suggest grabbing the next value as a String, then checking if it matches the integer format. 相反,我建议将下一个值作为String抓取,然后检查它是否与整数格式匹配。 If it does, then convert it, otherwise, handle it however you'd like. 如果是,那么转换它,否则,按照你的意愿处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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