当它应该为真时,递归返回false

时间:2013-04-02 07:25:13

标签: java if-statement boolean

我正在制作一个匹配递归的单词,但是我遇到了一个问题。如果语句为true,我有一个if语句将返回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"));
    }
}

当你运行它时,它会打印“运行这个方法”,但是它会返回false,当它应该返回true时...有人可以告诉我是什么导致了这个以及我将如何解决它?

3 个答案:

答案 0 :(得分:5)

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()不能多次使用,因为它无意中保持了呼叫之间的状态。上面提出的版本没有这个缺陷。

答案 1 :(得分:2)

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

答案 2 :(得分:0)

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

相关问题