All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cucumber.examples.java.calculator.RpnCalculator Maven / Gradle / Ivy

There is a newer version: 1.2.3
Show newest version
package cucumber.examples.java.calculator;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

import static java.util.Arrays.asList;

public class RpnCalculator {
    private final Deque stack = new LinkedList();
    private static final List OPS = asList("-", "+", "*", "/");

    public void push(Object arg) {
        if (OPS.contains(arg)) {
            Number y = stack.removeLast();
            Number x = stack.isEmpty() ? 0 : stack.removeLast();
            Double val = null;
            if (arg.equals("-")) {
                val = x.doubleValue() - y.doubleValue();
            } else if (arg.equals("+")) {
                val = x.doubleValue() + y.doubleValue();
            } else if (arg.equals("*")) {
                val = x.doubleValue() * y.doubleValue();
            } else if (arg.equals("/")) {
                val = x.doubleValue() / y.doubleValue();
            }
            push(val);
        } else {
            stack.add((Number) arg);
        }
    }

    public void PI() {
        push(Math.PI);
    }

    public Number value() {
        return stack.getLast();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy