【发布时间】: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