简体   繁体   中英

Can someone improve the recursive implementation of indexOf in Java?

I've been working on a Java summer assignment and there was a problem on recursively implementing the indexOf method in Java. Here is what I have so far:

public int rIndexOf(char ch, int fromPos)
{
    int charPos = fromPos;

    if (charPos >= myString.length() || myString.equals(""))
        return -1;
    else if (myString.charAt(charPos) == ch)
        return charPos;
    else
        return charPos + rIndexOf(ch, charPos + 1);
}

I seem to get values that are completely wrong, so I can only imagine it's a problem with incrementation or counting, but doesn't my code increment charPos by +1 each time? Or does it have to do with ASCII values of characters?

Also I was wondering if the line "charPos = fromPos" was necessary at all. Could I have just used fromPos throughout my code or would that violate the "pass-by reference not value" thing?

You could absolutely have used fromPos all the way through your code. Java never passed by reference, and you're not even changing the value of charPos anyway.

It's unclear why your final return statement adds charPos to the return value of the recursive call. Why isn't it just:

return rIndexOf(ch, charPos + 1);

? After all, suppose it finds it at position 3 - that's going to return 3, so you don't want to add 2 to the 3 in the previous call, then add 1 to the 5 and end up with 6...

This line:

return charPos + rIndexOf(ch, charPos + 1);

is flawed. Let's say myString is "the sun" and you call rIndexOf(' ', 0); Then you end up with:

0 + 1 + 2 + 3 instead of 3. Since charPos is incremented each time and you add it to itself. You should just change that line to:

return rIndexOf(ch, charPos + 1);

your last line is wrong, try this?

return rIndexOf(ch, charPos + 1)

also, this will create a huge stack in memory, not very efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM