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

In Java (Please help this homework~Thank you) One use of a Stack is to reverse t

ID: 3694258 • Letter: I

Question

In Java
(Please help this homework~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 Hello, Java, World):

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

import java.io.IOException;
import java.util.*;

class StringReversal
{
public static void main(String[] args)
{
boolean result = false;
Scanner input = new Scanner(System.in);
Stack <String> stack = new Stack <String>();
String temp = new String();
do
{
System.out.println("Enter a word or 'end' to quit:");
temp= input.nextLine();
stack.push(temp);
if(temp == "end")
result = false;
else
result = true;
}while(result);
  
System.out.print("You entered (in reverse): ");   
while(!stack.empty()) {
System.out.print(stack.pop());
System.out.print(" ");
}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote