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

use*_*517 1 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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

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

NPE*_*NPE 5

match()递归调用时,它忽略返回值.

因此如下:

       match(x, y);
Run Code Online (Sandbox Code Playgroud)

应该

       return match(x, y);
Run Code Online (Sandbox Code Playgroud)

我还建议你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"));
}
Run Code Online (Sandbox Code Playgroud)

您当前的版本match()不能多次使用,因为它无意中保持了呼叫之间的状态.上面提出的版本没有这个缺陷.