THINK FIRST·CODE LATER

← All labs

Evaluating postfix expressions with a stack

Problem

In postfix (reverse Polish) notation the operator follows its operands: 3 4 + 2 * means (3 + 4) × 2. No parentheses are ever needed.

Write Postfix with static long evaluate(String line) using a Deque<Long> as a stack: push numbers; for an operator pop the right operand, then the left, and push the result. Throw IllegalArgumentException with these messages: operator + needs two operands, division by zero, bad token x, 2 values left on the stack. main evaluates every non-empty input line.

For the input

3 4 + 2 *
5 1 2 + 4 * + 3 -
7 0 /
1 +
2 3
10 4 -

the program prints

3 4 + 2 * = 14
5 1 2 + 4 * + 3 - = 14
7 0 / -> error: division by zero
1 + -> error: operator + needs two operands
2 3 -> error: 2 values left on the stack
10 4 - = 6

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

3 4 + 2 *
5 1 2 + 4 * + 3 -
7 0 /
1 +
2 3
10 4 -
What your program must print for d4-3-data-1.txt
3 4 + 2 * = 14
5 1 2 + 4 * + 3 - = 14
7 0 / -> error: division by zero
1 + -> error: operator + needs two operands
2 3 -> error: 2 values left on the stack
10 4 - = 6

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

Windows PowerShell does not understand <:

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