繁体   English   中英

递归在应为true时返回false

[英]Recursion returning false when it should be true

我正在进行单词匹配递归,但是遇到了一个问题。 我有一个if语句,如果该语句为true,则将返回true。 我有一个system.print行进行测试,以查看它是否确实正确运行并且可以运行。 但是,如果该方法假定返回true,则返回false。 抱歉,如果我不清楚,希望我的代码将其清除。

public class A10 {

    public static int counter = 3;

    public static boolean match(String x, String y) {
        // If the x string's letter at place 'counter' is the same as y string's letter at place counter.
        if ((counter) >= x.length()) {
            System.out.println("RUNNING THIS METHOD");
            return true;
        }

        if (x.charAt(counter) == y.charAt(counter)) {
            counter++;
            match(x, y);
        }

        return false;

    }

    public static void main(String[] args) {
        System.out.println(match("asdfasdf", "asdfasdf"));
    }
}

当您运行它时,它将打印“ RUNNING THIS METHOD”,但是当它应返回true时它将返回false。有人可以告诉我是什么原因引起的,以及如何解决?

match()递归调用自身时,它将忽略返回值。

因此,以下内容:

       match(x, y);

应该

       return match(x, y);

我还建议您将counter变成一个参数,从而摆脱static

public static boolean match(String x, String y) {
    return match_helper(x, y, 0);
}

private static boolean match_helper(String x, String y, int counter) {
    if (counter >= x.length()) {
        return true;
    }

    if (x.charAt(counter) == y.charAt(counter)) {
        return match_helper(x, y, counter + 1);
    }

    return false;
}

public static void main(String[] args) {
    System.out.println(match("asdfasdf", "asdfasdf"));
}

您当前使用的match()版本不能多次使用,因为它会无意间保持两次调用之间的状态。 上面建议的版本没有此缺陷。

您应该return match(x, y); if您在第二秒内。 这是递归的主要原理。

仅被调用函数的第一个实例返回输出。 但是,只有计数器> = x.length()的实例才具有显示文本的副作用。

暂无
暂无

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

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