Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reverse Polish Notation sample
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
class Stack extends ArrayDeque<Double> {
@Override
public void push(Double v) {
System.out.println(toString() + "<-" + v);
super.push(v);
}
@Override
public Double pop() {
Double v = super.pop();
System.out.println(toString() + "->" + v);
return v;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
for (Double v: this) {
builder.append(v);
builder.append(" ");
}
builder.append("]");
return builder.toString();
}
}
interface Token {
Stack execute(Stack stack);
}
class Operand implements Token {
Double value;
Operand(Double val) {
value = val;
}
@Override
public Stack execute(Stack stack) {
stack.push(value);
return stack;
}
}
interface Operator extends Token {}
class Add implements Operator {
@Override
public Stack execute(Stack stack) {
if (stack != null) {
Double num1 = stack.pop();
Double num0 = stack.pop();
stack.push(num0 + num1);
}
return stack;
}
}
class Sub implements Operator {
@Override
public Stack execute(Stack stack) {
if (stack != null) {
Double num1 = stack.pop();
Double num0 = stack.pop();
stack.push(num0 - num1);
}
return stack;
}
}
class Mul implements Operator {
@Override
public Stack execute(Stack stack) {
if (stack != null) {
Double num1 = stack.pop();
Double num0 = stack.pop();
stack.push(num0 * num1);
}
return stack;
}
}
class Div implements Operator {
@Override
public Stack execute(Stack stack) {
if (stack != null) {
Double num1 = stack.pop();
Double num0 = stack.pop();
if (num1 != 0) {
stack.push(num0 / num1);
}
}
return stack;
}
}
public class Calculator {
private Map<String, Token> tokens;
{
tokens = new HashMap<>();
tokens.put("+", new Add());
tokens.put("-", new Sub());
tokens.put("*", new Mul());
tokens.put("/", new Div());
}
protected Token createToken(String s) {
Token result = tokens.get(s);
if (result == null) {
result = new Operand(Double.valueOf(s));
}
return result;
}
protected double execute(String input) {
Stack stack = new Stack();
String[] splits = input.split("\\s");
if (splited != null && 0 < splits.length) {
for (String s : splits) {
Token token = createToken(s);
token.execute(stack);
}
}
return stack.pop();
}
public static void main(String... args) {
StackMachine stackMachine = new StackMachine();
// (1 + 2) * 4 + (4 - 2) == 14
System.out.println("1 2 + 4 * 4 2 - + = "
+ stackMachine.execute("1 2 + 4 * 4 2 - +"));
// (1 + 4) * (3 + 7) / 5 == 10
System.out.println("1 4 + 3 7 + * 5 / = "
+ stackMachine.execute("1 4 + 3 7 + * 5 /"));
// 10 + 2 == 12
System.out.println("10 2 + = "
+ stackMachine.execute("10 2 +"));
// 10 / 2 == 5
System.out.println("10 2 / = "
+ stackMachine.execute("10 2 /"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.