I'm trying to make up the most compact solution for reading an integer from a user using only nextInt() method and the exceptions it throws to exclude errors... This is the code i have for now:
Scanner sn = new Scanner(System.in);
boolean inputNotNull = true;
while (inputNotNull) {
try {
int number = sn.nextInt();
System.out.printf("The number %d is power of 2: %b\n", number, isPowerOfTwo(number));
if (number == 0) {
inputNotNull = false;
}
}
catch(InputMismatchException e) {
System.err.println("Wrong input! Input only integer numbers please...");
}
}
So, what this is supposed to do is wait for an integer from a user. If the user enters 0 end the program. My idea was to try to exclude the scenario when the user enters something else than integer with use of InputMismatchException (I know it is not the best practice to catch RuntimeException). When the exception is raised an error message is printed, and the program returns to the while loop, asking again for the input as nothing happened.
Approach that I am using here has a flaw that when the user enters something that is not an integer value, program prints out the error message repeatedly, looping on forever.
How to avoid this?
As a side question how would you solve this problem that I am trying to solve?