romhail romhail - 3 months ago 17
Java Question

Recursion call in java causing incorrect behavior

I have a recursion call which is showing weird behavior.

public String recursionMethod() {
String repeatRun = null;
repeatRun = scanner.next();
if (!("Y".equals(repeatRun) || "N".equals(repeatRun))) {
System.out.println("Please enter the correct value. (Y/N)");
this.recursionMethod();
}
System.out.println("value of the entered variable->"+repeatRun);
return repeatRun;
}


When the method run for the first time, I enter value "no". As expected, it enters the if block and so it calls itself again asking to enter either "Y" or "N". This time, I enter "Y". It does not enter the if block again but the log prints like this.

Do you want to enter another directory? (Y/N)
no
Please enter the correct value. (Y/N)
Y
value of the entered variable->Y
value of the entered variable->no


This behavior is strange. Why is it picking the old value again? On running in debug mode it shows that after the control goes to the return line, it again goes to the line "this.recursionMethod()" which is inside the if block.

Please help me understand and also how to fix this so that my method does not return the previous value.

Answer

Try this :

    public String recursionMethod() {
        String repeatRun = null;
        repeatRun = scanner.next();
        if (!("Y".equals(repeatRun) || "N".equals(repeatRun))) {
            System.out.println("Please enter the correct value. (Y/N)");
            return this.recursionMethod();
        }
        System.out.println("value of the entered variable->"+repeatRun);
        return repeatRun;
    }

You forgot the return in the if block where you make the recursive call.