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.
returnkeyword only goes up one layer, to the place where the current execution of this method was called from.