【问题标题】:How do i validate integer as user input?如何验证整数作为用户输入?
【发布时间】:2020-07-22 03:06:39
【问题描述】:

我需要编写一个程序来验证用户输入是否为整数。我有一个可以实际工作的代码。但我真的不明白它是如何工作的。就像我知道如何使用,但不知道它在程序背后是如何工作的。你能向我解释一下它是如何工作的吗?

此外,其他一些替代方法可能会在这里使用 try catch,但我也不是必需的。所以有人可以向我解释一下吗?我还是 Java 新手。

真的很感激!

while(!read.hasNextInt())  // i understood this pard at which the conditions will return true/false
    {
        System.out.println("Enter integer only: ");
        read.next();  // without this line of code, i will get an infinite loop, BUT WHY?
    }

    int num = 0;  // declaration of variable
    num = read.nextInt();  // and this actually store the last digit user input in read.hasNextInt()
                           // why would'nt it prompt the user to enter again? because usually it does
    System.out.print(num); // and finally output the num value

【问题讨论】:

    标签: java validation input integer


    【解决方案1】:

    您的 while 循环通过阻塞检查扫描器是否没有可解析的整数。如果该条件为真,您只需调用 next() 即可清除扫描程序缓存。如果你没有清除缓存,它总是有一个整数,并且会继续无限期地阻塞。您需要调用 next() 或 nextInt() 之类的方法来使用该值。

    您对 nextInt() 的调用不会再次请求输入,因为您没有在 while 循环中消耗任何内容,您只是检查了输入是否为可解析整数。

    这是您的代码细分(伪);

    while scanner doesnt have a parseable integer {
        consume that non parseable value
    }
    consume the parseable integer
    

    【讨论】:

    • 对不起,我不确定我是否明白你的意思。所以 read.next();不会提示用户输入?
    猜你喜欢
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2022-09-28
    • 1970-01-01
    相关资源
    最近更新 更多