我正在练习练习18.10,《 Java编程简介》(综合版)的第十版,其内容如下:

编写一个递归方法,使用以下方法标头查找字符串中指定字母的出现次数:

public static int count(String str,char a)

因此,这是该方法的实现:

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

    if (str.charAt(str.length() - 1) != a)
        return 0;
    else
        return 1 + count(str.substring(0, str.length()), a);
}


我的基本情况是检查最后一个字符是否为指定的“重复出现的字符”;如果不是,则将“ 1”添加到字符串中字符出现的次数,然后递归调用count方法。

在适当的位置运行该程序会导致StackOverflowError。我猜这可能是由于无限递归造成的,而正是这段代码导致了问题:

str.substring(0, str.length())


麻烦的是,我不太确定我是否理解原因。 substring(int beginIndex,int endIndex)方法的描述读取

返回一个字符串,该字符串是该字符串的子字符串。子字符串从指定的beginIndex开始,并扩展到索引endIndex-1处的字符。

因此,按照我的编写方式,它应该返回一个子字符串,该子字符串包含原始字符串中除最后一个字符之外的每个字符,从而通过递归一次删除该字符串中的一个字符。

我可以看到为什么这可能有问题,因为当字符串的长度为1或0时,没有什么可告诉递归停止的,但是由于问题是StackOverflowError而不是IndexOutOfBounds异常,我有点丢失..

最佳答案

您应该使用[string - the_last_character](递归)调用该方法,因为已经检查并计算了最后一个字符。

此外,您必须检查字符串是否为空才能停止递归。

尝试这个:

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

  if(str.length() == 0) // here we have to stop the recursion as the string is empty!
      return 0;
  if (str.charAt(str.length() - 1) != a)
      return count(str.substring(0, str.length() - 1), a); // here we send the string - the last character which has been already checked.
  else
      return 1 + count(str.substring(0, str.length() - 1), a);
}

10-07 19:09
查看更多