Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Safely Scan for Integer Input? [duplicate]

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 InputMismatchExceptions 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?

like image 610
Maxpm Avatar asked Sep 16 '11 14:09

Maxpm


People also ask

How do I scan an integer?

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.

Is a Scanner method for integer input?

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.

Can a double take an int?

#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.


1 Answers

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.

like image 160
ChadNC Avatar answered Sep 18 '22 05:09

ChadNC