|
| 1 | +package com.iluwatar; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +public class App |
| 6 | +{ |
| 7 | + |
| 8 | + /** |
| 9 | + * |
| 10 | + * Expressions can be evaluated using prefix, infix or postfix notations |
| 11 | + * This sample uses postfix, where operator comes after the operands |
| 12 | + * |
| 13 | + */ |
| 14 | + public static void main( String[] args ) |
| 15 | + { |
| 16 | + String tokenString = "4 3 2 - 1 + *"; |
| 17 | + Stack<Expression> stack = new Stack<>(); |
| 18 | + |
| 19 | + String[] tokenList = tokenString.split(" "); |
| 20 | + for (String s : tokenList) { |
| 21 | + if (isOperator(s)) { |
| 22 | + Expression rightExpression = stack.pop(); |
| 23 | + Expression leftExpression = stack.pop(); |
| 24 | + System.out.println(String.format("popped from stack left: %d right: %d", |
| 25 | + leftExpression.interpret(), rightExpression.interpret())); |
| 26 | + Expression operator = getOperatorInstance(s, leftExpression, |
| 27 | + rightExpression); |
| 28 | + System.out.println(String.format("operator: %s", operator)); |
| 29 | + int result = operator.interpret(); |
| 30 | + NumberExpression resultExpression = new NumberExpression(result); |
| 31 | + stack.push(resultExpression); |
| 32 | + System.out.println(String.format("push result to stack: %d", resultExpression.interpret())); |
| 33 | + } else { |
| 34 | + Expression i = new NumberExpression(s); |
| 35 | + stack.push(i); |
| 36 | + System.out.println(String.format("push to stack: %d", i.interpret())); |
| 37 | + } |
| 38 | + } |
| 39 | + System.out.println(String.format("result: %d", stack.pop().interpret())); |
| 40 | + } |
| 41 | + |
| 42 | + public static boolean isOperator(String s) { |
| 43 | + if (s.equals("+") || s.equals("-") || s.equals("*")) |
| 44 | + return true; |
| 45 | + else |
| 46 | + return false; |
| 47 | + } |
| 48 | + |
| 49 | + public static Expression getOperatorInstance(String s, Expression left, |
| 50 | + Expression right) { |
| 51 | + switch (s) { |
| 52 | + case "+": |
| 53 | + return new PlusExpression(left, right); |
| 54 | + case "-": |
| 55 | + return new MinusExpression(left, right); |
| 56 | + case "*": |
| 57 | + return new MultiplyExpression(left, right); |
| 58 | + } |
| 59 | + return null; |
| 60 | + } |
| 61 | +} |
0 commit comments