递归函数中读取字符串的Java助手方法

递归函数中读取字符串的Java助手方法,java,recursion,Java,Recursion,我遇到了一个问题,在我已经在工作的递归函数中添加了一个helper方法,只使用了2个参数,当添加第3个(helper方法)时,我的代码中断并寻找解决方案。该程序使用扫描器对字符串进行键盘输入,对字符进行另一次输入,然后输出字母的出现次数。错误发生在第二条if语句和两条return语句上。在第二次键盘输入后,我得到错误: 线程“main”java.lang.StringIndexOutOfBoundsException中出现异常:字符串索引超出范围:-1 下面是一个可能的解决方案,可以帮助您避免索

我遇到了一个问题,在我已经在工作的递归函数中添加了一个helper方法,只使用了2个参数,当添加第3个(helper方法)时,我的代码中断并寻找解决方案。该程序使用扫描器对字符串进行键盘输入,对字符进行另一次输入,然后输出字母的出现次数。错误发生在第二条if语句和两条return语句上。在第二次键盘输入后,我得到错误:

线程“main”java.lang.StringIndexOutOfBoundsException中出现异常:字符串索引超出范围:-1


下面是一个可能的解决方案,可以帮助您避免索引超出范围:

public static int count(String str, char a, int high) {

    if (str == null || str.length() == 0) {
    // just to be extra safe, if we have an empty string or null 
        return 0;

    }
    //changed this end condition - now high describes how many steps we take before returning the answer
    if (high == 0) // to stop the recursion from infinitely looping
        return high;
    if (str.charAt(str.length() - 1) != a) // if the last character in the string is not equal to "a" subtract from count(substring)
        return count(str.substring(0, str.length() - 1), a, high - 1);
    else 
        return 1 + count(str.substring(0, str.length() - 1), a, high - 1); 
        // else add +1 to count for each instance of "a" in the string

}

您缺少递归方法的设计:首先,您应该关注一个问题,并为基本情况或多个情况定义它

我对这个问题的看法是,基本情况是空字符串(但在此之前,请确保它不是
null
),或者
high
设置为0

我对
high
的理解是,您可以使用它来设置要检查字符
a
出现情况的字符串的字符数;当字符串变大时,检查会更直接,将字符
a
搜索到
str.substring(0,high)
中的意义赋予
high
,但我试图保持它与您的代码类似

//we'll use high to "tell" the count method how many characters it will consider into the occurrences from the end of the given string
public static int count(String str, char a, int high) {
    //if the string isn't valid or high just tells it to stop, return 0 as there can be no occurrences of a in str
    if(str == null || str.equals("") || high == 0)
      return 0;

    // if the last character in the string is not equal to a, let's just shrink the string
    if (str.charAt(str.length() - 1) != a)
        return count(str.substring(0, str.length() - 1), a, high - 1);

    // otherwise add this 1 occurrence to the ones it will find in the rest of the string
    else 
        return 1 + count(str.substring(0, str.length() - 1), a, high - 1); 
}
main
中的调用将是:

System.out.println(character+ " occurred " + count(input, character, input.length()) + " times.");

请考虑以下情况:如果调用
str.length()-1
,空字符串将导致什么?然后想想当你停止递归时,很明显,你调用了
count
,即使是空字符串,字符串来自扫描器,正确的,取输入的长度并从中减去1?我对上一个程序没有任何问题,是在我使用第三个参数添加helper方法时。带有小字符串的笔+纸
aba
应该会向您显示问题-有时这种老式的调试工作速度足够快。否则,任何IDE都有一个调试器,这允许执行程序不要忘记,查看Java
子字符串
方法的描述和性质。结束了-exclusive@Devin,我添加了一个答案,其中high有一定的意义。请注意,它仅在high=input.length()时有效,否则检查是部分的。
System.out.println(character+ " occurred " + count(input, character, input.length()) + " times.");