recursion - Why does this Recursive Java Program not correctly reverse lines from a text file -


as follow question

where idea print lines file in reverse without using explicit data structure have implementation question. recursion suggested , here's have:

import java.io.*;  public class reverselines {    public reverselines() {    }     public void reverse(file filetoreverse, int n) {       try {          filereader fr = new filereader(filetoreverse);          bufferedreader br = new bufferedreader(fr);          string line = br.readline();          if (n > 0) {             reverse(filetoreverse, n - 1);          }          system.out.println(line);       } catch (exception e) {          system.out.println(e);       }    }     public static void main(string[] argv) {       reverselines testreverse = new reverselines();       file test = new file("money.txt");       testreverse.reverse(test, 3);    } } 

this code prints first line of money.txt 3 times instead of first 3 lines in reverse. frankly (and naively) don't see how recursion supposed work if readline(); used.

help appreciated...

thanks

you reading first line of file. change this:

import java.io.*;  public class reverselines {    public reverselines() {    }     public void reverse(bufferedreader br, int n) {       try {                      string line = br.readline();          if (n > 0) {             reverse(br, n - 1);             system.out.println(line);          }                    } catch (exception e) {          system.out.println(e);       }    }     public static void main(string[] argv) {       reverselines testreverse = new reverselines();       file test = new file("money.txt");        filereader fr = new filereader(test );       bufferedreader br = new bufferedreader(fr);         testreverse.reverse(br, 3);    } } 

Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -