我正在尝试完全理解该方法的工作原理,请参阅下面的代码:
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));
首先检查索引零处的字符是否为空格,然后再次调用自身(这使得它递归)从索引1开始的s的子字符串作为参数有效地从“多个空格”中更改参数“to”“空格数”并且直到参数的长度()达到0为止。我没有得到的是为什么它不返回01000000100100000010(最后一个0用于终止循环的空字符串s)但是4?我无法看到代码中的哪个位置总结了
返回的1(s.charAt(0) == ' ' ? 1 : 0)
并忽略0。 请告诉我我的推理缺少什么。
非常感谢
的Grzegorz(格雷格)
答案 0 :(得分:2)
(s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1))
这个基本上总结了0
和1
s。
记下方法的返回值int
。 4
的返回值非常好。
换句话说:
0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 = 4
答案 1 :(得分:2)
由于该方法返回一个int而不是一个字符串,因此它会添加数字,而不是连接为字符/字符串。即
0+1+0+0+0+0+0+0+1+0+0+1+0+0+0+0+0+0+1+0 == 4
不
"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"+"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"
== "01000000100100000010"
下面的返回一个int,因为countpaces返回一个int
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
答案 2 :(得分: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 )
}
}
答案 3 :(得分:0)
递归的意思是函数被一遍又一遍地调用,你可以粗略地说它是某种循环。
if (s.length() == 0)
return 0;
此代码正在停止递归函数的条件(因为此时递归停止),当提供的字符串的长度为0时,它将返回0.这里没什么可解释的,我认为这很明显。
这部分是递归函数的核心部分:
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
s.charAt(0) == ' ' ? 1 : 0
使用ternary operator,它检查字符串中的第一个字符是否为空格,如果是,则使用值1,否则使用0。
countspaces(s.substring(1))
再次调用该函数,子字符串删除第一个字符。
函数返回int
值为0或1,它将返回的值相加,如您所知,x + 0 = x
,所以只有第一个字符为空格(函数返回1)的情况才会影响您的最终值结果
这个调用一直发生,直到函数自己传递空字符串,当它到达停止条件时,它返回通过调用堆栈,从三元运算符求和返回的值和值,最后返回预期值结果