THINK FIRST·CODE LATER

← All labs

A Generic Stack Driven by Commands

Problem

Write a generic class GenericStack<E> backed by a private ArrayList<E>, with:

  • void push(E item)
  • E pop() and E peek() — both throw IllegalStateException when the stack is empty
  • boolean isEmpty() and int size()
  • String toString() — the elements from top to bottom separated by single spaces, or empty when there are none

Then write a program that creates a GenericStack<String>, reads a number q and then q commands, one per line:

Command Output
push X nothing (X is a single word)
pop Popped: X, or Error: empty stack
peek Top: X, or Error: empty stack
size Size: n

The program must catch the IllegalStateException to print the error message. After the last command, print Final (top first): followed by the stack's toString().

Input:

6
push red
push green
peek
pop
push blue
size

Output:

Top: green
Popped: green
Size: 2
Final (top first): blue red

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d2-2-data-1.txt

6
push red
push green
peek
pop
push blue
size
What your program must print for d2-2-data-1.txt
Top: green
Popped: green
Size: 2
Final (top first): blue red

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d2-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content d2-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.