【发布时间】:2014-05-03 14:29:33
【问题描述】:
我找不到这个练习的正确解决方案,这是任务:
(数组中指定字符的出现次数) 编写递归方法 查找指定字符在数组中出现的次数。 您需要 定义以下两个方法。第二个是递归辅助方法。
public static int count(char[] chars, char ch)
public static int count(char[] chars, char ch, int high)
编写一个测试程序,提示用户在一行中输入一个字符列表, 和一个字符,并显示该字符在列表中出现的次数。
1) 只有添加另一个参数(int index)才能解决它,但是如果不添加另一个参数或使用 for 循环,我怎么能做到呢?
2) 为什么会有辅助方法?我不明白递归中辅助方法的目的。
这是我的解决方案:
package occurencesinarray;
import java.util.Scanner;
public class Start {
public static void main(String[] args){
System.out.println("Enter few characters: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
char[] chars = new char[s.length()];
for(int i = 0; i < s.length(); i++){
chars[i] = s.charAt(i);
}
System.out.println("Enter desired character: ");
char ch = scan.nextLine().charAt(0);
System.out.println(count(chars, ch));
}
public static int count(char[] chars, char ch){
return count(chars, ch, 0, 0);
}
public static int count(char[] chars, char ch, int high, int index){
if(index == chars.length){
return high;
}
if(chars[index] == ch){
return count(chars, ch, high + 1, index + 1);
} else{
return count(chars, ch, high, index + 1);
}
}
}
【问题讨论】:
标签: java recursion helpermethods