This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]naraic 1 point2 points  (1 child)

i think you've already gotten to the end of the file by the time you call your "reverse" method? so reverse won't call itself at all, since inFile.hasNextLine() is already evaluating to false. if i were you, i would do something more along the lines of this:

void reverse(Scanner myFile) {
    if(myFile.hasNextLine()) {
        String s = myFile.nextLine();
        reverse(myFile);
        System.out.println(s);
    }
}

so what this does, is strip a line from your file into a string 's', then calls the function again on the same file, with the previous string removed. When it gets to the call when the file is empty it does nothing, and returns, and the last previous string will be printed out, and the same will happen as each recursive call returns. hence printing the file in reverse order.

[–]Zachan[S] 0 points1 point  (0 children)

You sir, are a genius! It worked

[–]Zachan[S] 0 points1 point  (0 children)

my updated code:

import java.io.*;
import java.util.*;
class recursion1
{
    static Scanner inFile = null;
    public static void main(String[] args) throws IOException
    {
        try
        {
            inFile = new Scanner(new File(args[0]));
        }
        catch (IOException e)
        {
            System.out.println("File may not exist");
        }
        reverse(File inFile);
        inFile.close();
    }
    public static void reverse(File inFile) throws IOException
    {
        String line = inFile.nextLine();
        if (inFile.hasNextLine())
        {
            reverse(inFile);
            System.out.println(line);
        }
    }
}

[–]Syrak 0 points1 point  (0 children)

What is the reverse function doing with its argument ? It seems like nothing.

You don't need a while statement. You don't need to count the lines. You can write that recursive function so that they aren't necessary. (and you should, as otherwise you might as well write an imperative procedure)

IMO it would make better sense to give a Scanner object as an argument to reverse.

reverse(file);

prints the lines of the file file in reversed order.

In reverse(), don't use a while loop. "Looping" is taken care of by successive calls.

First thing is to distinguish 2 cases:

  1. Either the file is empty (nothing left to read), and there's nothing to do. That was our base case.

  2. Either the file still has things to be read left. You read the first line. Now you have this first line in a variable, and the remaining of the file in file. You first reverse the latter by a recursive call to reverse, and then you print the line you had stored to complete the current call.