给定一个字符串,递归计算(无循环)字符串中小写“x”字符的数量。
countX(“xxhixx”)→4
countX(“xhixhix”)→3
countX(“hi”)→0
我的尝试:
public int countX(String str) {
int sum = 1;
if(str.length()-1==0){
return sum;
}
else{
if(str.charAt(0)=='x'){
return sum+countX(str.substring(1));
}
if(str.charAt(0)!='x'){
return countX(str.substring(1));
}
}
}
我收到以下错误消息:This method must return a result of type int.
甚至不确定我的基本情况是否正确。任何提示?
答案 0 :(得分:3)
要求通过函数的每个代码路径都必须返回一个值,并且编译器对你有点过于迂腐:
if(str.charAt(0)=='x'){
return sum+countX(str.substring(1));
}
if(str.charAt(0)!='x'){
return countX(str.substring(1));
}
// <--- there's no return value here
可以说,编译器可以弄清楚两个if语句是否耗尽了所有可能性,但它没有。
帮助编译器的一种方法是将两个ifs重新表示为单个if-else:
if(str.charAt(0)=='x') {
return sum+countX(str.substring(1));
} else {
return countX(str.substring(1));
}
答案 1 :(得分:1)
如何使用fall through而不是显式拥有if/else
,这在某些情况下可能会混淆编译器
public static int countX(final String str) {
//base case
if(str.length() == 0) {
return 0;
}
else if(str.length() == 1) {
return str.charAt(0) == 'x' ? 1 : 0;
}
//recursive step
return str.charAt(0) == 'x' ? 1 + countX(str.substring(1)) : countX(str.substring(1));
}
答案 2 :(得分:0)
并非所有代码路径都有返回(从哑编译器的角度来看)。在一个开始总结似乎也是错误的。考虑:
public int countX(String str) {
if(str.length()==0){
return 0;
} else if(str.charAt(0)=='x'){
return 1 + countX(str.substring(1));
} else {
assert str.charAt(0)!='x';
return countX(str.substring(1));
}
}
或者:
public int countX(String str) {
if(str.length()==0){
return 0;
}
if(str.charAt(0)=='x'){
return 1 + countX(str.substring(1));
}
assert str.charAt(0)!='x';
return countX(str.substring(1));
}
炒鱼的方法很多:
public int countX(String str) {
return str.isEmpty() ? 0 : (
(str.charAt(0)=='x' ? 1 : 0)
+ countX(str.substring(1))
);
}
想要更简洁,更不易读?
public int countX(String str) {
return str.isEmpty()?0:countX(str.substring(1))+str.charAt(0)=='x'?1:0;
}
对不起,我正在寻找代码混淆玩具的乐趣。
答案 3 :(得分:0)
这样的事情应该这样做。
public int countX(String str) {
int sum = 0;
if(str.length()-1!=0){
sum = countX(str.substring(1));
if(str.charAt(0)=='x'){
sum += 1;
}
}
return sum;
}
你的问题是,在某些情况下,没有回报。 避免这种情况的一种方法是在方法结束时使用单个返回指令,或者只需在代码中添加一些其他情况,如下所示:
[...]
else{
if(str.charAt(0)=='x'){
return sum+countX(str.substring(1));
}else{
return countX(str.substring(1));
}
}
[...]
答案 4 :(得分:0)
public int countX(String str) {
if (str.length() == 0) return 0;
int sum = 0;
if(str.charAt(0) == 'x') sum = sum + 1;
return sum + countX(str.substring(1));
}