如何验证整数作为用户输入



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

此外,其他一些替代方案可能在这里使用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

while循环通过阻塞检查Scanner是否没有可解析的Integer。如果该条件为true,则只需调用next((即可清除Scanners缓存。如果你不清除缓存,它总是有一个整数,并且会无限期地继续阻塞。您需要调用像next((或nextInt((这样的方法来使用该值。

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

这是您的代码(伪代码(的分解;

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

最新更新