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
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;
}





