如何使此函数返回我要寻找的值?

时间:2019-11-25 16:38:34

标签: java if-statement recursion return

我制作了一个函数,该函数旨在递归计算函数中特定字符的数量。

conda install -c conda-forge glpk

如何在函数末尾添加return语句,以返回我在函数内部“计数”的整数?

4 个答案:

答案 0 :(得分:1)

在方法末尾不需要多余的return语句,您得到的错误是因为编译器不确信您已涵盖所有情况。

最简单的解决方法是用c替换与else的第二个比较。字符等于c或不是,就不需要单独检查。

例如

public static int countCharInString(String s, char c, int index) {
    if (index == s.length()) {
        return 0;
    }
    if (s.charAt(index) == c) {
        return 1 + countCharInString(s, c, index + 1);
    } else {
        return countCharInString(s, c, index + 1);
    }
}

答案 1 :(得分:0)

我将使用for循环,如果需要递归,请检查是否     索引+1> s.length() 如果是这种情况,则递归应返回

答案 2 :(得分:0)

您需要一个参数来跟踪您的跑步总数。在函数中添加一个参数,每次找到该字符时该参数都会增加。然后返回该数字,而不是返回0

答案 3 :(得分:0)

在这里使用递归对我来说没有意义。字符串中的字符数将为s.length()。

但是,由于这是您的要求-我相信您希望包含一些字符-我认为这是经典的“重新发明”车轮程序。尽管我不喜欢这些,但这里重要的是要了解正在发生的事情。

首先,您不需要为索引设置变量...因为您始终将其设置为0。所以只需使用0。

第二,让我们使用substring,这样我们就不必转换为char并处理字符/字符串比较等。

public static int countCharInString(String s, String c) {
  // This will only happen when the string is empty to begin with, our we're done with recursion. Since we add this to another number in recursion - it works for our purpose
  if (s.length() == 0) {
    return 0;
  }

  // If we have a match, increment add add to our recursive sum
  if ((s.substring(0, 1).equals(c))) {
    return 1 + countCharInString(s.substring(1), c);
  }

  // do the final return and invoke recursion
  return countCharInString(s.substring(1), c);
}