In my code i
is declared outside of the try-catch
block so that the return statement won't have any scope issues. Also it is given the value -1, so if an exception occurs then the function returns -1 to the caller.
protected int readInt(String prompt) {
int i=-1;
System.out.print(prompt);
try {
i = keyboard.nextInt();
keyboard.nextLine();
} catch (java.util.InputMismatchException e) {
System.out.println("Error: Insert a number.");
keyboard.next();
}
return i;
}