我创建了一个递归方法,该方法将在文本文件ch
中查找特定字符file1
(由用户输入)的出现次数
该方法将接收file1
,ch
,count
的出现次数,我将其作为参数以避免重设,x
作为文件长度
public static int rec(File file1, char ch, int count, int x) throws IOException {
char current;
FileInputStream fis = new FileInputStream(file1);
current = (char) fis.read();
if (x == 1 && current == ch) {
return ++count; //1
} else {
return rec(file1, ch, count, x - 1) + count; //2
}
}
所以事情是,它不返回出现的次数(不执行return 2),而只是从返回1返回count
。
我该如何解决?
edit:之所以使用递归,是因为该代码是分配的一部分,需要使用迭代和递归来解决问题
答案 0 :(得分:2)
多个问题:
fis
,因此总是只检查文件的第一个字符x
我想像的检查来检查...)以下是伪代码/自由文本中的示例,解释了如何实现它
具有递归:
FileInputStream fis = new FileInputStream(file1);
public int count(fis, char) {
read a char
check if fis is fully read from
return 0 if fis is empty
if char matches return 1 + count(fis, char)
else return count(fis, char)
}
无递归:
FileInputStream fis = new FileInputStream(file1);
while (read char && fis is not empty) {
if (char matches) {
increment count by one
}
}