Java中的数据验证和扫描仪 [英] Data Validation and Scanners in Java

查看:36
本文介绍了Java中的数据验证和扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于数据验证和扫描器的问题.以下代码检查用户输入.除整数以外的任何内容都不允许,并且要求用户重新输入一个值.我的问题是代码仅在以下情况下有效扫描器在while循环中声明.如果扫描器在外部声明,则程序将无限执行.为什么?

I have a question regarding data validation and scanners.The following piece of code checks userinput.Anything other than an integer is not allowed and the user is asked to re-enter a value.My question is that the code works only if the scanner is declared within the while loop.The program executes infinitely if the scanner is declared outside.Why is that?Thanks.

int UserInp;
    boolean dataType=false;
    while(dataType==false)
    {
        Scanner sc=new Scanner(System.in);
        try
        {

    System.out.print("\nEnter a number: ");
    UserInp=sc.nextInt();

    dataType=true;
        }
        catch(Exception JavaInputMismatch)
        {

            System.out.println("Option not available.Try again.");

        }

    }

推荐答案

有趣的问题!

发生的事情是,扫描程序尝试将非整数转换为整数,并意识到它不能-从而引发InputMismatchException.但是,只有翻译成功后,它才会越过令牌.

What happens is that the Scanner attempts to translate the non-integer to an integer, and realizes it can't -- so it throws an InputMismatchException. However, it only advances past the token if the translation was successful.

意味着,无效字符串仍在输入缓冲区中,并且每次循环并尝试调用nextInt()时,转换都会失败.您永远不会将dataType设置为true,因此可以无限循环.

Meaning, the invalid string is still in the input buffer, and it will fail the translation every single time you loop and try to call nextInt(). You never set dataType to true, and so you loop infinitely.

要查看实际效果,您可以在catch块中获取任意内容并将其打印出来:

To see this in action, you can grab the arbitrary content in your catch block and print it out:

catch(Exception JavaInputMismatch){
    System.out.println( sc.next() );
    System.out.println("Option not available.Try again.");
}

实际上,在输入无效后,我们得到以下信息:

Indeed, after invalid input, we get the following:

Enter a number: hello
hello
Option not available.Try again.

Enter a number:

我们不会无限循环.这是因为对next()的调用从输入缓冲区中获取了该值,并将扫描仪的指针移至该缓冲区中的下一个插槽,该插槽现在为空.因此,在这种情况下nextInt()将等待输入.

And we don't loop infinitely. This is because the call to next() grabbed the value from the input buffer and advanced the scanner's pointer into that buffer to the next slot, which is now empty. So nextInt() will wait for input in that case.

哦,如果在循环中初始化,它能正常工作的原因是扫描程序将始终开始读取新的输入.扫描程序不会在实例之间共享状态,因此由于重新初始化,上次迭代的缓冲区中的"hello"不在下一个迭代的缓冲区中.

Oh, and the reason it works fine if you initialize in the loop is that the scanner will always start reading input fresh; scanners don't share state across instances, so the "hello" that was in the buffer for the previous iteration isn't in the buffer for the next one due to the reinitialization.

从技术上来说,它仍然在标准输入缓冲区中,但是扫描器指向该缓冲区的指针超出了无效字符串的范围,因为它将开始读取任何不存在的 new 输入输入.

Technically, it's still in the standard input buffer, but the scanner's pointer into that buffer is beyond the invalid string because it will start reading any new input, not existing input.

这篇关于Java中的数据验证和扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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