/** Driver.java -- Let's illustrate stack operations. * Let's create and evaluate an expression. */ import java.io.*; import java.util.*; public class Driver { public static void main(String [] args) throws IOException { BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter a postfix expression: "); String line = kbd.readLine(); System.out.println("You entered " + line); StringTokenizer tok = new StringTokenizer(line, " "); LinkedListStack stack = new LinkedListStack(); // 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. // The stack holds Objects, so we'll let them be String. We could also // have used Double. Because of the necessary conversions (operations can // only be done on double), the code is a little tedious. // 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((String) stack.pop()); a = Double.parseDouble((String) stack.pop()); stack.push("" + (a+b)); } else if (token.equals("-")) { b = Double.parseDouble((String) stack.pop()); a = Double.parseDouble((String) stack.pop()); stack.push("" + (a-b)); } else if (token.equals("*")) { b = Double.parseDouble((String) stack.pop()); a = Double.parseDouble((String) stack.pop()); stack.push("" + (a*b)); } else if (token.equals("/")) { b = Double.parseDouble((String) stack.pop()); a = Double.parseDouble((String) stack.pop()); stack.push("" + (a/b)); } else stack.push(token); } System.out.println("The value of the expression is " + Double.parseDouble((String) stack.pop())); } }