Java 递归方法如何计算字符串中的空白?

Java 递归方法如何计算字符串中的空白?,java,oop,recursion,Java,Oop,Recursion,我试图完全理解该方法的工作原理,请参见下面的代码: public static void main(String[] args) { System.out.println(countspaces("a number of spaces ")); } public static int countspaces(String s) { if (s.length() == 0) return 0; else return (s.charAt(0

我试图完全理解该方法的工作原理,请参见下面的代码:

public static void main(String[] args) {
    System.out.println(countspaces("a number of spaces "));
}

public static int countspaces(String s) {
    if (s.length() == 0)
        return 0;
    else
        return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
}
我已经用BlueJ调试了这个方法。该行:

return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
首先检查索引0处的字符是否为空白,然后它再次调用自身(这使其具有递归性),将从索引1开始的s的子字符串作为参数,有效地将参数从“空格数”更改为“空格数”,直到参数的长度()达到0为止。我不明白的是为什么它不返回010000010000010(最后一个0表示终止循环的空字符串s),而是返回4?我看不出它在代码中对返回的1求和的位置

(s.charAt(0) == ' ' ? 1 : 0)
并忽略0。 请告诉我我的推理遗漏了什么

非常感谢

格泽戈兹(格雷格)

这一个基本上总结了
0
s和
1
s

注意方法的返回值,它是
int
4
的返回值非常好

换言之:

0+1+0+0+0+0+0+0+0+1+0+0+0+1+0+0+0+0+0 +1+0=4


由于该方法返回的是int,而不是字符串,因此它将数字相加,而不是作为字符/字符串串联。即

0+1+0+0+0+0+0+0+1+0+0+1+0+0+0+0+0+0+1+0 == 4
不是

下面返回一个int,因为countspaces返回一个int

return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));

下面尝试用“英语”编写函数,以帮助您理解:

int countspaces( string ) {

    if string has no characters {
        return 0
    }
    else {

        if first character in string is a space 

        add 1 

        otherwise

        add 0

        to result of countspaces( string_with_first_character_removed )
    }
}

递归的要点是函数被反复调用,你可以粗略地说它是某种循环

if (s.length() == 0)
    return 0;
这段代码是递归函数的停止条件(因为递归在此点停止),当提供的字符串长度为0时,它将返回0。这里没什么要解释的,我认为这是很明显的

这部分是递归函数的核心部分:

return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
s.charAt(0)=''?1:0
使用a,它检查字符串中的第一个字符是否为空格,如果为真,则使用值1,否则使用0

countspaces(s.substring(1))
再次调用该函数,使用删除第一个字符的子字符串

函数返回0或1的
int
值,它对返回的值求和,如您所知,
x+0=x
,因此只有第一个字符是空格的情况(函数返回1)才会影响最终结果


此调用一直发生,直到函数自身传递空字符串,当它达到停止条件时,返回调用堆栈,将返回的值和来自三元运算符的值相加,并最终返回预期结果。

这将是
+
。在数字加法中,将0添加到和中不会改变它+,非字符串包含,例如1+1==2,而不是1+1==11。我很好奇,为什么要用递归来计算空间?这是某种类型的作业吗?是的,作为考试准备的一部分。谢谢Vixen,现在这很有意义!感谢Adam,我错过的是int中的返回类型,而不是整数字符串。
if (s.length() == 0)
    return 0;
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));