1

My code cannot reverse each line of the input. It should be look like: Input:

abc
def
ghi

Output:

cba
fed
ihg

How to modify it?

import java.*;
import java.util.Scanner;

public class Reverse {
    public static void main(String[]args) {
        Scanner in = new Scanner(System.in);
        String s = new String();

        while (in.hasNextLine()) {
            s += in.nextLine() + "\n";
        }

        StringBuffer r = new StringBuffer(s);
        r = r.reverse();
        System.out.println(r);
    }
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Andrew
  • 33
  • 1
  • 7

1 Answers1

0

You are reversing the characters in the string. You need to reverse the characters on each line.

Scanner in = new Scanner(System.in);
String s = new String();

while(in.hasNextLine()){
     StringBuffer buf = new StringBuffer(in.nextLine());
     s += buf.reverse() + "\n";
}
System.out.println(s);
Mark
  • 1,374
  • 11
  • 12