I am required to write a program that will validate the user input as integer. I have a code that will actaully work. But i dont really understand how it works.. Is like i know how to use, but have no idea how it works behind the program. Can you please explain to me how it actually work?
Also, some other alternatives may be using try catch here but i am not required too.. so can anyone please explain to me? i am still new to Java.
Really appreciate that !
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
Your while loop checks if the Scanner doesn't have a parsable Integer by blocking. If that condition is true, you are simply calling next() which clears the Scanners cache. If you didn't clear the cache it would always have an integer and would continue to block indefinitely. You need to call a method like next() or nextInt() to consume the value.
The call to nextInt() that you have doesn't request input again because you haven't consumed anything in your while loop, you just checked if the input was a parsable Integer.
This is the breakdown of your code (pseudo);
while scanner doesnt have a parseable integer {
consume that non parseable value
}
consume the parseable integer
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments