I have a while with a boolean sentinel. If an integer is entered, which is what is requested, it works fine, but if anything else is entered the loop repeats endlessly, printing the question "type 3 integers" and "make it an integer". The input.nextInt is supposed to put the program on hold, but I don't know why, it doesn't.
boolean c=false;
try
{
while(!c)
{
System.out.println("Escriba 3 numeros enteros");
if(entrada.hasNextInt())
{
x=entrada.nextInt();
c=true;
}
else
System.out.println("Que sea entero, try again");
}
}
catch(InputMismatchException exc)
{
System.out.println(exc);
}
Why does it produce the infinite loop? The scanner blocks the program waiting for data to be entered into the buffer. When a data is entered, the buffer is no longer empty and the lock ends. If it is not a number, the method
hasNextInt()
returns false, so it does not enter the condition and continues with the execution of the while. And since the entered data was not read, the buffer continues with a value. In the next iteration the scanner does not block and that produces the infinite loop.What is missing is, if what is entered is not a number, then read the entered data so that the buffer is empty again and the scanner blocks the program:
You can better handle errors
Firstly you are getting a
InputMismatchException
, this is because theScanner
indicates in this case that the retrieved token does not match the expected type.After this error el
while
continues but what causes the infinite loop is that elScanner
has the value left in the buffer that is not of integer type as expected and the value of c will never change to false.The most common way to do what you want is to determine when the input of the n number of elements is done.
but in this case first validate if the element is of type determined in this case integer, which you can determine in this way:
Therefore this would be an option to solve the problem:
What if you better put the try catch block inside the body of your while and not outside?