Write a program that reads in words and prints them out in r
Write a program that reads in words and prints them out in reverse order. Complete this code.
Complete the following file:
ReverseInput.java
import java.util.ArrayList;
import java.util.Scanner;
public class ReverseInput
{
public static void main(String[] args)
{
ArrayList<String> words = new ArrayList<String>();
Scanner in = new Scanner(System.in);
// Read input into words
while (in.hasNext())
{
. . .
}
// Reverse input
for (. . .)
{
System.out.print(words.get(i) + \" \");
}
}
}
Solution
import java.util.*;
public class reverseInput
{
public static void main(String[] args) {
String words;
//Accept Input from user
System.out.println(\"Enter Input:\");
Scanner in = new Scanner(System.in);
words=in.nextLine();
Stack <String> stack = new Stack <String>();
String[] temp;
String delimiter = \" \";
// given string will be split by the argument delimiter provided.
temp = words.split(delimiter);
// push substring to stack
for(int i =0; i < temp.length ; i++)
{
stack.push(temp[i]);
}
System.out.println(\"\ Original string: \" + words);
System.out.print(\"Reverse word string: \");
while(!stack.empty()) {
System.out.print(stack.pop());
System.out.print(\" \");
}
System.out.println(\"\ \");
}
}

