DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Isaque has posted 1 posts at DZone. View Full User Profile

Scanner Class: Exception Handling For Reading Integers

09.30.2009
| 11854 views |
  • submit to reddit
        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;
    }