Scanner Class: Exception Handling For Reading Integers
Join the DZone community and get the full member experience.
Join For FreeThis 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;
}
Opinions expressed by DZone contributors are their own.
Comments