Search code examples
javarecursionstack-overflow

Why am I encountering stackoverflow in Java?


I have a int, "count" that adds one after each recursion, but I also have an if statement that stops the recursion once the int is equal to, or greater than another integer. Somehow that if statement is ignored.

public static boolean wildcard(String x, String y, int substring, int count) {
    if (count >= y.length()){
        System.out.println("asdf");
        return true;
    }

    if (x.charAt(count) == y.charAt(count)){
        System.out.println("ALSKDFJKL");
        return wildcard(x, y, substring, count++);
    }
    if (y.charAt(count) == '*'){
        return wildcard(x.substring(substring), y, substring++, count);


    System.out.println("wildcard end");
    return false;
    }

Solution

  • Instead of return wildcard(x, y, substring, count++); try return wildcard(x, y, substring, ++count);

    count++ is a post increment (meaning it will increment AFTER the method returns)

    You will probably also want to update return wildcard(x.substring(substring), y, substring++, count); for the same reason.

    Also, your last if statement is broken...I think the System.out and return false want to be outside the if block