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;
            try
                {
                    integer = in.nextInt();
                }
                catch(Exception e)
                {
                    System.out.printf("only numbers are allowed");
                    in.nextLine();
                    integer = readOnlyIntegers(in);
                }
        return integer;
    }
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}