Java: A stack machine that reports errors

A tiny calculator that works on a stack, reporting each error by line and carrying on.

What to build

A stack machine that runs commands and reports errors without stopping.

Requirements

  • Commands: push N, add, sub, mul, div (each pops b, then a, and pushes a op b; div is integer division), pop, print (prints the top value).
  • Errors, as an unchecked exception of your own caught in the main loop: stack underflow when there are too few values, division by zero, and unknown command: WORD for anything else. Print line K: MESSAGE; a failed command leaves the stack unchanged.
  • At the end print stack: followed by the values from bottom to top separated by spaces (stack: empty if none).

Input

Line 1: q. Then q commands.

Output

The printed values and error lines, then the stack.

Constraints

1 ≤ q ≤ 200; values fit in a long.

Example

Input:

6
push 7
push 3
sub
print
mul
push 2

Output:

4
line 5: stack underflow
stack: 4 2

Why it works

Throwing from the operation and catching in the loop keeps the error handling in one place, and checking before popping guarantees that a failed command leaves the stack as it was.

Examples

Example 1 · Input
6
push 7
push 3
sub
print
mul
push 2
Expected output
4
line 5: stack underflow
stack: 4 2
Example 2 · Input
4
push 1
push 0
div
jump
Expected output
line 3: division by zero
line 4: unknown command: jump
stack: 1 0

Hints

Hint 1

Make StackMachineException extend RuntimeException and throw it for underflow, division by zero and unknown commands.

Hint 2

Check that a command can succeed before changing the stack, so a failed command changes nothing.

Solution

Show one correct solution (try it yourself first)
import java.util.Scanner;

public class Main {
    static class StackMachineException extends RuntimeException {
        StackMachineException(String message) {
            super(message);
        }
    }

    static long[] stack = new long[256];
    static int size = 0;

    static void need(int k) {
        if (size < k) throw new StackMachineException("stack underflow");
    }

    static void run(String line) {
        String[] p = line.trim().split(" ");
        switch (p[0]) {
            case "push" -> stack[size++] = Long.parseLong(p[1]);
            case "pop" -> {
                need(1);
                size--;
            }
            case "print" -> {
                need(1);
                System.out.println(stack[size - 1]);
            }
            case "add", "sub", "mul", "div" -> {
                need(2);
                long b = stack[size - 1];
                long a = stack[size - 2];
                if (p[0].equals("div") && b == 0) throw new StackMachineException("division by zero");
                long r = switch (p[0]) {
                    case "add" -> a + b;
                    case "sub" -> a - b;
                    case "mul" -> a * b;
                    default -> a / b;
                };
                size -= 2;
                stack[size++] = r;
            }
            default -> throw new StackMachineException("unknown command: " + p[0]);
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = Integer.parseInt(in.nextLine().trim());
        for (int i = 1; i <= q; i++) {
            try {
                run(in.nextLine());
            } catch (StackMachineException e) {
                System.out.println("line " + i + ": " + e.getMessage());
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) sb.append(i == 0 ? "" : " ").append(stack[i]);
        System.out.println("stack: " + (size == 0 ? "empty" : sb.toString()));
    }
}

Lesson: Exceptions →