Paul Etscheit Paul Etscheit - 1 month ago 8
Java Question

Recursive method returning an int not compiling

I'm learning Java at the moment and have a task where I should create a method that keeps asking the user for input until one of two keywords are entered. It should then, depending on that return an int.

public static int getCommand(){
String command = IOTools.readString("Enter Command!");
if (command.equals("exit")){
return 1;
} else if (command.equals("shift")){
return 0;
} else {
getCommand();
}
}


The problem I'm having is that eclipse tells me to either change the return type to void or add a return statement after the if block.
enter image description here
Is there something wrong with my recursive approach?

Answer

you need to add a return type in last case

public static int getCommand(){
    String command = IOTools.readString("Enter Command!");
    if (command.equals("exit")){
        return 1;
    } else if (command.equals("shift")){
        return 0;
    } else {
        return getCommand();
    }
}

this function getCommand(); call is returning an int value but not in else case so if the control falls inside your else case then your recursive functions calls will be executed though there is no assurance that getCommand(); will return an int value due to else case so compiler detects that hence the error and according to this case where return type is not void , java says

Every execution path in a function must lead to a RETURN statement