/** Evaluating postfix expression. @author Jed Yang, 2018-01-19 */ import java.util.List; import java.util.ArrayList; import java.util.Scanner; // Stack: push/pop/peek/isEmpty/EmptyStackException // Queue: add/remove/element/isEmpty/NoSuchElementException public class Postfix { /** Evaluates a correct space-delimited postfix expression. Note: no error checking -- assumes expression is corretly formatted. */ public static int evaluatePostfix(String expression) { Stack stack = new CarlStack(); String[] array = expression.split(" "); for (String s : array) { if (s.equals("+")) { int secondNum = stack.pop(); int firstNum = stack.pop(); int answer = firstNum + secondNum; stack.push(answer); } else if (s.equals("-")) { int secondNum = stack.pop(); int firstNum = stack.pop(); int answer = firstNum - secondNum; stack.push(answer); } else if (s.equals("*")) { int secondNum = stack.pop(); int firstNum = stack.pop(); int answer = firstNum * secondNum; stack.push(answer); } else if (s.equals("/")) { int secondNum = stack.pop(); int firstNum = stack.pop(); int answer = firstNum / secondNum; stack.push(answer); } else { int number = Integer.parseInt(s); stack.push(number); } } int answer = stack.pop(); return answer; } public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.print("Postfix expression, please: "); String expression = kb.nextLine(); // expression = "1 2 + 3 4 - 5 6 * - 7 8 9 * - * +"; System.out.println(evaluatePostfix(expression)); } }