user1692517
user1692517

Reputation: 1152

Recursion returning false when it should be true

I'm in the process of making a word matching recursion, however I ran into a problem. I have an if statement that would return true if the statement is true. I have a system.print line to test to see if it actually ran correctly and it does. However when the method is suppose to return true, it returns false. Sorry if I'm being unclear, I hope my code clears it up.

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"));
    }
}

When you run it, it will print "RUNNING THIS METHOD", but then it will return false, when it should return true... Can someone tell me what's causing this and how I would fix it?

Upvotes: 1

Views: 3808

Answers (3)

NPE
NPE

Reputation: 500317

When match() calls itself recursively, it disregards the return value.

Thus the following:

       match(x, y);

should be

       return match(x, y);

I would also suggest that you turn counter into an argument, thereby getting rid of the static state:

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"));
}

Your current version of match() can't be used more than once since it inadvertently keeps state between calls. The proposed version above does not have this flaw.

Upvotes: 6

Firzen
Firzen

Reputation: 2095

Only the first instance of called function returns output. But only the instance with counter >= x.length() has side effect to display the text.

Upvotes: 0

sp00m
sp00m

Reputation: 48817

You should return match(x, y); within your second if. This is the main principle of recursion.

Upvotes: 2

Related Questions