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

In java language Question 1 One use of a Stack is to reverse the order of input.

ID: 3694341 • Letter: I

Question

In java language

Question 1

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

Question 2

Create a Java class using generics: ItemPair. Objects of this class hold a pair of two items that are the same type. For example, an ItemPair can hold two Integers or it could hold two Strings or it could hold two ArrayLists, etc. An ItemPair could not, however, hold an Integer and a String.

Write the following using generics:

the class header

instance data

a constructor that takes both items in as parameters

getters and setters for each item in the pair

Explanation / Answer

Answer -1

import java.util.*;

public class StackDemo {

static void showpush(Stack st, String a) {
st.push(new String(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}

static void showpop(Stack st) {
System.out.print("pop -> ");
String a = (String) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}

public static void main(String args[])
{
String str;
int status=0;
Scanner input = new Scanner(System.in);
Stack st = new Stack();
System.out.println("stack: " + st);
do
{
System.out.println("Enter a word or 'end' to quit : ");
str=input.next();
if(str.compareTo("end")!=0)
{
showpush(st, str);
}
}while(str.compareTo("end")!=0);
  
do
{
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
status=1;
}
}while(status!=1);
}
}

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