简体   繁体   English

递归方法的输出错误

[英]get wrong output of a recursive method

    public static int getIndexOf(char ch, String str) {
    if (str == null || str.equals("")) {
        return 0;
     //base case
    }else{
        char first = str.charAt(0);
        if (ch != first) {
            return -1;
     //returns -1 when the character cannot be found within the string
        }else{
            int rest = str.length() - 1;
            if (str.charAt(rest) == ch) {
                return rest; 
            }
            return lastIndexOf(ch, str.substring(0, rest));
            //recursive case
        }
    }
}

This my method which returns the index of the input character of the input string. 此my方法返回输入字符串的输入字符的索引。 However, when I run it in the interaction plane, it returns wrong number. 但是,当我在交互平面中运行它时,它返回错误的数字。 For example, when I enter 'a' and "peach", it is supposed to return 2, but it returns -1. 例如,当我输入“ a”和“桃子”时,应该返回2,但返回-1。 This method should return -1 only when the character cannot be found in the string. 仅当在字符串中找不到字符时,此方法才应返回-1。 Can anyone tell me how to deal with it? 谁能告诉我该如何处理? Thank you! 谢谢!

Well why don't you step through the logic and see what happens. 好吧,为什么不逐步理解逻辑,看看会发生什么。

getIndexOf('a', "peach")

Method goes in, string isn't null or empty so it falls through to the next line of code. 方法进入,字符串不为null或为空,因此它会进入下一行代码。

char first = str.charAt(0); // this is 'p'

if (ch != first) {  // is 'p' equal to 'a'? no. so return -1
        return -1;

And then the rest of your logic will never execute. 然后,其余逻辑将永远不会执行。 Can you see how to fix this problem? 您能看到解决此问题的方法吗?

your following portion of code means that it will check for the first character of the string if it is matching otherwise it will return -1. 您后面的代码部分意味着,如果匹配,它将检查字符串的第一个字符,否则将返回-1。

char first = str.charAt(0);
        if (ch != first) {
            return -1;

this says that if character at 0th index doesn't match then send -1 so as 'p' in "peach" isn't matching with 'a' so it is return -1. 这表示如果第0个索引处的字符不匹配,则发送-1,因为“ peach”中的“ p”与“ a”不匹配,因此返回-1。

did you get it? 你明白了吗?

The output's not wrong, the implementation is! 输出没有错,实现是!

Think in words first. 首先用语言思考。 If the desired character is the first character in the string, then the result is zero. 如果所需字符是字符串中的第一个字符,则结果为零。 Otherwise it's (1 + the index in the string that remains after cutting off the first character). 否则为(1 +截断第一个字符后剩余的字符串索引)。 Now code the words: 现在编写单词:

return (str.charAt(0) == ch) ? 0 : 1 + getIndexOf(ch, str.substring(1));

This doesn't yet handle the case where the character is not in the string at all. 这还不能处理字符根本不在字符串中的情况。 Here the charAt(0) call will eventually throw IndexOutOfBoundsException because str doesn't have one! 此处的charAt(0)调用最终将引发IndexOutOfBoundsException因为str没有一个!

The cleanest way to handle this case is to catch the exception. 处理这种情况的最干净的方法是捕获异常。 So you's have two functions: mustGetIndexOf , which is the recursive relation above, and getIndexOf , which calls the one above inside a try {} catch() {} , returning -1 in that case. 因此,您有两个函数: mustGetIndexOf (它是上面的递归关系)和getIndexOf (它在try {} catch() {}内调用上面的那个try {} catch() {} ,在这种情况下返回-1。

Of course if you don't want to allow the exception, you can test the recursive call's result with if for the special case of -1 . 当然,如果您不想允许该异常,则可以针对-1的特殊情况使用if测试递归调用的结果。 The code is uglier, but it will work. 代码很丑陋,但是可以正常工作。 Whenever a -1 is seen, return -1 again. 每当-1看到,返回-1一次。 This propagates the -1 all the way back to the caller. 这会将-1一直传播回调用方。 The exception "unwinds" the recursive calls on the stack in a similar manner, just with one chop instead of the gradual call-by-call way your if statements will do it. 异常以类似的方式“展开”堆栈上的递归调用,只需要一次切碎,而不是用if语句将其逐步调用的方式。

I won't give you full code so you can continue to learn. 我不会提供完整的代码,因此您可以继续学习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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