【发布时间】:2017-08-19 05:46:15
【问题描述】:
我正在尝试递归编写下面的 Java 代码:
public static int count(String word) {
int numValue = 0;
int length = word.length();
for(int i=0; i<length; i++){
String alpha = "abcdefghijklmnopqrstuvwxyz";
String letter = (word.substring(0 + i,1 + i));
numValue = numValue + alpha.indexOf(letter) + 1;
}
return numValue;
}
public static void main(String[] args) {
System.out.println(count("abc"));
}
函数返回输入字符串参数中每个字母的索引之和。
我正在尝试以递归方式编写相同的代码,谁能指出我哪里出错了?
public static int count(int numValue, int i, String word) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
if( i >= word.length()){
return numValue;
}
else{
String letter = (word.substring(0 + i,1 + i));
numValue = numValue + alpha.indexOf(letter) + 1;
count(numValue, i=i+1, word);
}
return numValue;
}
public static void main(String[] args) {
System.out.println(count(0,0, "abc"));
}
【问题讨论】:
-
如果可以迭代,为什么还要递归呢?通常使用循环比所有这些递归调用更快......
-
你的递归函数永远不会存储或使用递归调用的值做任何事情
-
欢迎来到 Stack Overflow!寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误和重现它所需的最短代码在问题本身。没有明确问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example。