Scanner scanner = new Scanner();
int number = 1;
do
{
try
{
option = scanner.nextInt();
}
catch (InputMismatchException exception)
{
System.out.println("Integers only, please.");
}
}
while (number != 0);
Despite the exception handling, this code will enter an infinite loop when non-integer input is given. Instead of Scanner
pausing to collect input in the next iteration, it simply continues throwing InputMismatchException
s until the program is killed.
What's the best way to scan for integer (or another type, I suppose) input, discarding invalid input and continuing the loop normally?
To read integers from console, use Scanner class. Scanner myInput = new Scanner( System.in ); Allow a use to add an integer using the nextInt() method. System.
Scanner is a class in java. util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.
#1) Typecasting In this way of conversion, double is typecast to int by assigning double value to an int variable. Here, Java primitive type double is bigger in size than data type int. Thus, this typecasting is called 'down-casting' as we are converting bigger data type values to the comparatively smaller data type.
You should check whether or not the input can be parsed as an int before attempting to assign the input's value to an int. You should not be using an exception to determine whether or not the input is correct it is bad practice and should be avoided.
if(scanner.hasNextInt()){
option = scanner.nextInt();
}else{
System.out.printLn("your message");
}
This way you can check whether or not the input can be interpreted as an int and if so assign the value and if not display a message. Calling that method does not advance the scanner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With