简体   繁体   English

Java中的递归调用导致不正确的行为

[英]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". 当方法第一次运行时,我输入值“ no”。 As expected, it enters the if block and so it calls itself again asking to enter either "Y" or "N". 如预期的那样,它进入if块,因此再次调用自身,要求输入“ Y”或“ N”。 This time, I enter "Y". 这次,我输入“ Y”。 It does not enter the if block again but the log prints like this. 它不会再次输入if块,但是日志将像这样打印。

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. 在调试模式下运行时,它表明控件转到返回行之后,它再次转到if块内的“ this.recursionMethod()”行。

Please help me understand and also how to fix this so that my method does not return the previous value. 请帮助我理解以及如何解决此问题,以便我的方法不返回以前的值。

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. 您在进行递归调用的if块中忘记了返回值。

When you check if the typed value is Y or N, if the value is wrong, you ask the user to type again a new value, making a recursive call. 当您检查键入的值是Y还是N时,如果该值是错误的,则要求用户再次键入新值,从而进行递归调用。 However, when this recurisve call ends, the method continues till the end, printing the value typed first. 但是,当该recallsve调用结束时,该方法将继续进行到最后,并打印首先键入的值。 The right implementation should be this: 正确的实现应该是这样的:

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

return repeatRun;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM