0

So my program reads in a file and displays it just fine, but when I reverse it, it only displays on one single line.

import java.io.*;
public class palinPractice
{
  public static void main(String args[]) throws IOException
  {
    BufferedReader br = new BufferedReader(new FileReader("data.txt"));
    PrintWriter    pr = new PrintWriter(new FileWriter("JCdata.txt"));
    String rec;
    String temp = "";

    while((rec = br.readLine()) != null)  // Reads Through
    {
      System.out.println(rec);
      /*for(int i = rec.length()-1;i>=0;i--)  // Reverse
      {
        temp = temp + rec.charAt(i);
      }*/
    }
    System.out.println(temp);

I commented out the reverse statement, but there it is. When I read in the file and display it, it works and it has spaces and new lines where they are supposed to be, but when reversed it displays on one long single line.

Any help would be appreciated.

2 Answers2

0

Your System.out.println(rec) is in a while loop, and rec is being reassigned to br.readLine(). Each time you read a new line, the first thing you do is print that out.

Meanwhile, if you uncomment your reverse stuff, you're building temp into a big reversed string of the entire document and waiting until you end the while loop to print anything.

There are two possible solutions, depending on what you intend to do with this.

If you don't need to keep the total reverse value, you can print each reversed line one at a time. Change the body of your while loop to look like this:

while((rec = br.readLine()) != null) {
    System.out.println(rec);
    temp = "";
    for(int i = rec.length()-1;i>=0;--i) {
        temp = temp + rec.charAt(i);
    }
   System.out.println(temp);
}

The second option is to just build up one big string and print it all in one shot at the end. If you want to do this though, you'll have to append in some '\n' characters.

So, right after your for loop that reverses the line, as the last line of your while loop, add this line:

temp = temp + System.getProperty("line.separator");

Now after reading each line and reversing it, you add a line break into the string before reading the next line. When you finish and exit the while loop, a single System.out.println will take care of it all.

That'd look like this:

while((rec = br.readLine()) != null) {
    System.out.println(rec);
    for(int i = rec.length()-1; i>=0; --i) {
        temp = temp + rec.charAt(i);
    }
    temp = temp + System.getProperty("line.separator");
}
System.out.println(temp);
nhgrif
  • 61,578
  • 25
  • 134
  • 173
0

Try

while((rec = br.readLine()) != null)  // Reads Through
{
  System.out.println(rec);
  for(int i = rec.length()-1;i>=0;i--)  // Reverse
  {
    temp = temp + rec.charAt(i);
  }
  temp = temp + System.getProperty("line.separator");
}
JoeC
  • 1,850
  • 14
  • 12