Write a short Java program that takes all the lines input to standard input and writes them to standard output in reverse order. That is, each line is output in the correct order, but the ordering of the lines is reversed.
package java_problems_datastructures;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReverseOrder {
public static ArrayList<String> takeInput() {
Scanner input = new Scanner(System.in);
// initiate an array and save the elements in that array
ArrayList<String> listOfLines = new ArrayList<String>(4);
System.out.println("Please enter 5 lines of strings: ");
while (listOfLines.size() < 5) {
listOfLines.add(input.nextLine());
}
input.close();
return listOfLines;
}
// calling this method on each element in the array
public static String reverseTheLine(String str) {
// convert the string to char array
char[] in = str.toCharArray();
int beginIndex = 0;
int end = in.length - 1;
char temp;
while (end > beginIndex) {
temp = in[beginIndex];
in[beginIndex] = in[end];
in[end] = temp;
end--;
beginIndex++;
}
// convert reversed characters into string
return new String(in);
}
public static void printLinesInReverse(ArrayList<String> al) {
List<String> reverseValues = new ArrayList<String>();
//Store each reversed line into this new array
for (String ls : al) {
reverseValues.add(reverseTheLine(ls));
}
System.out.println("\nModified(reversed) lines mainting same order: \n");
// printout our new array
for (String str : reverseValues) {
System.out.println(str);
}
}
public static void main(String args[]) {
// calling the method
printLinesInReverse(takeInput());
}
}
Output:
Please enter 5 lines of strings:
Racecar
shallow
hello
kishore
laksj2432 4l jwlw543223
Modified(reversed) lines mainting same order:
racecaR
wollahs
olleh
erohsik
322345wlwj l4 2342jskal