Java 如何验证整数作为用户输入?
我需要写一个程序,将验证作为整数的用户输入。我有一个代码,它确实可以工作。但是我真的不明白它是怎么工作的。。就像我知道如何使用,但不知道它在程序背后是如何工作的。你能给我解释一下它是怎么工作的吗 此外,其他一些替代方案可能会在这里使用try-catch,但我也不是必需的。。谁能给我解释一下吗?我对Java还是新手 非常感谢Java 如何验证整数作为用户输入?,java,validation,input,integer,Java,Validation,Input,Integer,我需要写一个程序,将验证作为整数的用户输入。我有一个代码,它确实可以工作。但是我真的不明白它是怎么工作的。。就像我知道如何使用,但不知道它在程序背后是如何工作的。你能给我解释一下它是怎么工作的吗 此外,其他一些替代方案可能会在这里使用try-catch,但我也不是必需的。。谁能给我解释一下吗?我对Java还是新手 非常感谢 while(!read.hasNextInt()) // i understood this pard at which the conditions will retur
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循环通过阻塞检查扫描仪是否没有可解析的整数。如果该条件为true,则只需调用next()即可清除扫描仪缓存。如果不清除缓存,它将始终具有一个整数,并将继续无限期地阻塞。您需要调用next()或nextInt()之类的方法来使用该值 您对nextInt()的调用不会再次请求输入,因为您在while循环中没有消耗任何内容,您只需检查输入是否为可解析整数 这是代码的分解(伪代码)
对不起,我不知道我是否明白你的意思。因此,请阅读;不会提示用户输入吗?
while scanner doesnt have a parseable integer {
consume that non parseable value
}
consume the parseable integer