递归方法有多个返回值

时间:2018-09-24 19:04:17

标签: java recursion

我创建了一个递归方法,该方法将在文本文件ch中查找特定字符file1(由用户输入)的出现次数

该方法将接收file1chcount的出现次数,我将其作为参数以避免重设,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:之所以使用递归,是因为该代码是分配的一部分,需要使用迭代和递归来解决问题

1 个答案:

答案 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
    }
}
相关问题