Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA homework help thank you! One use of a Stack is to reverse the order of inpu

ID: 3694695 • Letter: J

Question

JAVA homework help thank you!

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

Explanation / Answer

/* Java code using stack to reverse the order of input words */

import java.util.*;

public class ReverseOrderWords {

public static void main(String[] args){
  
Scanner s=new Scanner(System.in);
String a;
StringBuilder strBuilder= new StringBuilder();

while(true){

System.out.print("Enter a word or 'end' to quit: ");

a = s.nextLine();
if(a.equals("end")) break;
strBuilder.append(a);
strBuilder.append(" ");

}
  
// stringbuilder to string
String str= strBuilder.toString();

// creating stack
Stack sta=new Stack();

// using stringtokenizer
StringTokenizer st=new StringTokenizer(str);

//pushing words in stack
while(st.hasMoreTokens()){
sta.push(st.nextElement());
}


System.out.println(" Original string : " + str);
System.out.print("Reverse Order Words : ");

// popping stack to reverse the string
while(!sta.empty()){
System.out.print(sta.pop());
System.out.print(" ");
}

System.out.println(" ");


}
}