Вопрос

I currently have a method that is supposed to take two strings and then check if one string exists as a substring in other. It doesn't check both ways so the way in which I pass my strings to the method determines what string is looked for in the other.

Currently I am getting a stackoverflow error.

public boolean checkMatch(String text, String regex, int i){

    int regexL = regex.length();

        if(i == regexL){
            return true;
        }   

        System.out.println(text.charAt(i) + " " + regex.charAt(i));

        if(text.charAt(i) == regex.charAt(i)){
            return checkMatch(text, regex, i++);
        }
        else if(text.charAt(i) != regex.charAt(i)){

            if(text.substring(1) == ""){
                return false;
            }               
            else if(text.substring(1) != ""){
                return checkMatch(text.substring(1), regex, 0);
            }
        }
        return false;

}

I am running a test using my first name as an example.

@Test public void test_52() {
    assertEquals(true, checkMatch("Samual", "mu", 0));
}

the console looks like this after it overflows.

S m

a m

m m

m m

m m

etc

Where am I going wrong? Am I iterating wrong? The stack trace shows that it seems to be getting caught on this line.

return checkMatch(text, regex, i++);

But the defect point is rarely the point of failure. Sorry for the wall of text and code.

Это было полезно?

Решение

I don't know if the rest is correct, but here is one error: i++increments i after it was evaluated. You call your function with the same value every time. You probably mean ++i.

Другие советы

You have:

return checkMatch(text, regex, i++);

You mean:

return checkMatch(text, regex, ++i);

Or:

return checkMatch(text, regex, i + 1);

The problem with i++ there is post-increment evaluates to i before the increment, so you're just getting stuck without advancing i, and eventually the recursion overflows the stack.

Had you printed i in your debugging output, the problem may have been clearer.

You can just use the indexOf method:

 System.out.println("Samual".indexOf("mu") > 0);

Output:

true
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top