THINK FIRST·CODE LATER

← All labs

Browser back and forward with two stacks

Problem

Write BrowserHistory. The browser starts on home. Commands until the end of input:

  • visit PAGE — the current page goes on the back stack, and the forward stack is cleared;
  • back — the current page goes on the forward stack and the top of the back stack becomes current (cannot go back if empty);
  • forward — the reverse (cannot go forward);
  • anything else prints unknown command ….

After each successful command print the page and both stack sizes; at the end print the current page and the back stack.

For the input

visit news visit mail back back back forward visit shop forward

the program prints

visit -> news  (back 1, forward 0)
visit -> mail  (back 2, forward 0)
back -> news  (back 1, forward 1)
back -> home  (back 0, forward 2)
cannot go back
forward -> news  (back 1, forward 1)
visit -> shop  (back 2, forward 0)
cannot go forward
Now on: shop
Back stack (top first): [news, home]

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.

d4-5-data-1.txt

visit news visit mail back back back forward visit shop forward
What your program must print for d4-5-data-1.txt
visit -> news  (back 1, forward 0)
visit -> mail  (back 2, forward 0)
back -> news  (back 1, forward 1)
back -> home  (back 0, forward 2)
cannot go back
forward -> news  (back 1, forward 1)
visit -> shop  (back 2, forward 0)
cannot go forward
Now on: shop
Back stack (top first): [news, home]

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 < d4-5-data-1.txt

Windows PowerShell does not understand <:

Get-Content d4-5-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.