SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Java Primer
Exercise:
Exercises
Question:26 | ISBN:9781118771334 | Edition: 6

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.