Java 如何使此函数返回值I';我在找什么?
我做了一个函数,它可以递归地计算函数中特定字符的数量Java 如何使此函数返回值I';我在找什么?,java,if-statement,recursion,return,Java,If Statement,Recursion,Return,我做了一个函数,它可以递归地计算函数中特定字符的数量 public static int countCharInString(String s, char c) { return countCharInString(s, c, 0); } public static int countCharInString(String s, char c, int index) { if(index==s.length())
public static int countCharInString(String s, char c)
{
return countCharInString(s, c, 0);
}
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);
}
if(s.charAt(index)!=c)
{
return countCharInString(s, c, index+1);
}
}
我怎样才能在函数的末尾放一个return语句,返回我在函数中“计数”的整数?我会使用for循环,如果需要递归,请检查 索引+1>s.长度()
如果是这种情况,递归应该返回,那么在方法末尾不需要额外的return语句,您得到的错误是因为编译器不相信您已经涵盖了所有情况 最简单的解决方法是用
else
替换与c
的第二次比较。无论字符是否等于c
,都不需要单独检查
e、 g
你需要有一个参数来记录你的跑步总量。在函数中添加一个参数,每次找到该字符时,该参数都会递增。然后返回那个数字,而不是在这里使用递归返回0,这对我来说没有意义。字符串中的字符数将为's.length()' 然而,由于这是您的要求-我相信您需要一些字符的计数-我认为这是一个经典的“重新发明”车轮程序。虽然我不喜欢这些,但重要的是要了解正在发生的事情 首先,索引不需要变量。。。因为您总是将其设置为0。所以只需使用0 其次,让我们使用
子字符串
,这样我们就不必转换为字符,也不必处理字符/字符串比较等
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);
}
第一个方法的要点是什么?还有-为什么使用递归?这是一个要求吗?@sleepToken是的,这是递归练习的一部分。我知道在内存方面,它比在循环中运行更糟糕,但这是练习的一部分。@sleepToken第一个函数只接收字符串和字符,我需要第二个函数将索引添加到其输入中。有没有办法只用一个函数就可以做到这一点?@YonatanRafaely如果您不传入索引,而是使用
substring()
从后续调用中删除您已经检查过的字符,那么您可以在一个函数中实现这一点。这就是为什么我出现编译错误的原因。谢谢我通常使用for循环而不是递归,但在这种情况下,我必须在递归中进行练习。谢谢你的意见!
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);
}