Over a million developers have joined DZone.

Scanner Class: Exception Handling For Reading Integers

This method prevents a common user error: input chars where have to input numbers.
Basically, it uses recursion and some other inner properties of the class Scanner, like the method nextline().
It Receives a input stream as argument.

public int readOnlyIntegers(Scanner in) 

        int integer = 0;
                    integer = in.nextInt();
                catch(Exception e)
                    System.out.printf("only numbers are allowed");
                    integer = readOnlyIntegers(in);
        return integer;

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}