Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

Think about what happens if an InputMismatchException occurs.

Your code will catch it, print "Error: Insert a number.". And then what? Your function is declared to return an int and it has a path in which it does not return anything.

You should either return a value that cannot be returned otherwise, and indicates an error, or rethrow the exception.

After your catch block add a finally block with your return statement:

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

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

    }

}

http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

If a method having return type, JVM should expect for a return value after calling this method, In this case return is with only try {}. suppose any case its not executing all statements in try segment then there is no return type , thats why you got compiler error. You can either put return inside catch segment and try segment or outside of both try and catch

Since you are consuming InputMismatchException, it will not know what to return in case the InputMismatchException is thrown. You can either throw some Exception or have some return in the catch block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top