More than one return in a recursion method

I created a recursive method which will find the number of occurrences of a specific characterch (input by the user) in a text file file1 .

the method will receive file1,ch,countthe number of occurrences,I put it as argument to avoid resetting it,xas file length

public static int rec(File file1, char ch, int count, int x) throws IOException {
    char current;
    FileInputStream fis = new FileInputStream(file1);
    current = (char);
    if (x == 1 && current == ch) {
        return ++count;          //1
    } else {
        return rec(file1, ch, count, x - 1) + count; //2 

So the thing is it doesn't return the number of occurrences (it doesn't execute return 2), it just returns count from return 1. How can I fix this ?

edit: I used recursion because this code is part of an assignment which requires solving the problem using iteration and recursion

1 answer

  • answered 2018-09-24 19:13 luk2302

    Multiple issues:

    • you create a new fis for every recursive call and therefore ALWAYS check only the first character of the file
    • you never check for the end of the file (you do so via the x check I imagine...)
    • your logic is quite weird and you use too many paramenters
    • you use recursion

    What follows will be too examples in pseud-code / free text explaining how you could implement it

    with recursion:

    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)

    without recursion:

    FileInputStream fis = new FileInputStream(file1);
    while (read char && fis is not empty) { 
        if (char matches) {
            increment count by one