import java.util.Scanner; import java.util.StringTokenizer; import java.util.Stack; /** Driver.java * Let's create and evaluate an expression to illustrate stack operations. * Rather than implementing our own stack class, let's use the API's version. * We'll have a stack of strings, in other words: Stack. * Alternatively, we could have stored Double objects in the stack. */ public class Driver { public static void main(String [] args) { Scanner kbd = new Scanner(System.in); System.out.printf("Please enter a postfix expression: "); String line = kbd.nextLine(); System.out.printf("You entered %s\n", line); StringTokenizer tok = new StringTokenizer(line, " "); Stack stack = new Stack(); // Each time we encounter an operator, we pop 2 numbers, evaluate, and // push the result on the stack. If we encounter a number, we just push // it. When the input is done, our answer should be the only number left // on the stack. // Note that we pop items off the stack in reverse order to how they // were pushed. while (tok.hasMoreTokens()) { String token = tok.nextToken(); double a, b; if (token.equals("+")) { b = Double.parseDouble(stack.pop()); a = Double.parseDouble(stack.pop()); stack.push("" + (a+b)); } else if (token.equals("-")) { b = Double.parseDouble(stack.pop()); a = Double.parseDouble(stack.pop()); stack.push("" + (a-b)); } else if (token.equals("*")) { b = Double.parseDouble(stack.pop()); a = Double.parseDouble(stack.pop()); stack.push("" + (a*b)); } else if (token.equals("/")) { b = Double.parseDouble(stack.pop()); a = Double.parseDouble(stack.pop()); stack.push("" + (a/b)); } else stack.push(token); } System.out.printf("The value of the expression is %f\n", Double.parseDouble(stack.pop())); } }