Search code examples
javaintreturntry-catchinputmismatchexception

Eclipse asks for a return statement though I have one


protected int readInt(String prompt) {
    try {
        System.out.print(prompt);
        int i = keyboard.nextInt();
        keyboard.nextLine();
        return i;

    } catch (java.util.InputMismatchException e) {
        System.out.println("Error: Insert a number.");
    }
}

Hi! Eclipse gives me this error at the method readInt(): "This method must return a result of type int." and gives the example solutions "Add return statement" and "Change return type to void". I've tried to put the return i statement outside the try-and-catch loop, but when I do, the return statement can't find the variable i.

I've been struggeling with this for a while now, and can't seem to make it work... I would appreciate any help! Thank you.


Solution

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