I am facing a problem taking all the lines from standard input and write them to standard output in reverse order. That is output each line in the reverse order of input.
Below is my code:
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
//get input
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by
\"-1\":");
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
append += input + " ";
}
sc.close();
System.out.println("The current append: " + append);
String stringArray[] = append.split(" strings" + "");
System.out.println("\n\nThe reverse order is:\n");
for (int i = 0; i < stringArray.length; i++) {
System.out.println(stringArray[i]);
}
}
}
When I run my code with sample inputs like below:
Type some text with line breaks, end by "-1":
My name is John.
David is my best friend.
James also is my best friend.
-1
I get the following output:
The current append: My name is John. David is my best friend. James also is my best friend.
The reverse order is:
My name is John. David is my best friend. James also is my best friend.
Whereas, the required output is something like below:
The current append: My name is John. David is my best friend. James also is my best friend.
The reverse order is:
James also is my best friend.
David is my best friend.
My name is John.
Can anyone help me to check what is wrong with my code and fix it?