Sunday 1 October 2017

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.

Problem:

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.

Solution:

package com.basics;

import java.util.Scanner;

public class LineReversal {


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

    System.out.printf("Please specify how many lines you want to enter: ");       
    String[] input = new String[scanner.nextInt()];
    scanner.nextLine(); //consuming the <enter> from input above

    for (int i = 0; i < input.length; i++) {
        input[i] = scanner.nextLine();
    }

    System.out.printf("\nYour input:\n");
    for (String s : input) {
        System.out.println(s);
    }

    System.out.printf("\nReverse Order:\n");
    for (int i = input.length - 1; i >= 0 ; i--) {
    System.out.println(input[i]);
}
}

}


Output:

Please specify how many lines you want to enter: 3
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.

Your input:
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.

Reverse Order:
correct order, but the ordering of the lines is reversed.
writes them to standard output in reverse order. That is, each line is output in the
Write a short Java program that takes all the lines input to standard input and

No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...