One use of a Stack is to reverse the order of input Write a

One use of a Stack is to reverse the order of input. Write a complete method that reads a series of Strings from the user. The user enters \"end\" to stop inputting words. Then, output the Strings in reverse order of how they were entered. Do not output the String \"end\". Use a stack to accomplish this task. Invoke only the methods push, pop, peek, and isEmpty on the stack object. Here is an example of how the program would run (user input in blue): Enter a word or \'end\' to quit: Hello Enter a word or \'end\' to quit: Java Enter a word or \'end\' to quit: World Enter a word or \'end\' to quit: end You entered (in reverse): World Java Hello

Solution

StringStackTest.java

import java.util.Scanner;

import com.examples.ArrayStack;


public class StringStackTest {

  
   public static void main(String[] args) {
       readStrings();
   }
   public static void readStrings(){
       Scanner scan = new Scanner(System.in);
       ArrayStack<String> stack = new ArrayStack<String>();
       String s = \"\";
       while(!s.equalsIgnoreCase(\"end\")){
       System.out.print(\"Enter a word or end to \'quit\': \");
       s = scan.next();
       if(!s.equalsIgnoreCase(\"end\")){
       stack.push(s);
       }
       }
       System.out.println(\"Yo entered (in reverse): \");
   while (!stack.isEmpty()) {
   String word = stack.peek();
   System.out.println(word);
   stack.pop();
   }
   }

}

Output:

Enter a word or end to \'quit\': Hello
Enter a word or end to \'quit\': Java
Enter a word or end to \'quit\': World
Enter a word or end to \'quit\': end
Yo entered (in reverse):
World
Java
Hello

 One use of a Stack is to reverse the order of input. Write a complete method that reads a series of Strings from the user. The user enters \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site