Java中的数据验证和扫描程序

12d*_*990 4 java validation java.util.scanner

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

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.");

        }

    }
Run Code Online (Sandbox Code Playgroud)

Pur*_*rag 5

有趣的问题!

会发生什么是扫描程序尝试将非整数转换为整数,并意识到它不能 - 所以它抛出一个InputMismatchException.但是,如果翻译成功,它只会超过令牌.

意思是,无效字符串仍然在输入缓冲区中,并且每次循环并尝试调用时它都将无法进行转换nextInt().你永远不会设置dataType为true,所以你无限循环.

要查看此操作,您可以获取catch块中的任意内容并将其打印出来:

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

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

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

Enter a number:
Run Code Online (Sandbox Code Playgroud)

我们不会无限循环.这是因为调用next()从输入缓冲区中获取值并将扫描器的指针前进到该缓冲区中的下一个插槽,现在为空.所以nextInt()在那种情况下会等待输入.

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

从技术上讲,它仍然在标准输入缓冲区中,但扫描仪指向该缓冲区的指针超出了无效字符串,因为它将开始读取任何输入,而不是现有输入.