//PostfixMalik.java //simplified version of PostfixCalculator of page 408. //input a string of a valid postfix expression of integers, evaluate it. //assumes input is a valid postfix expression (i.e. no error checking is done). import java.util.*; import javax.swing.*; public class PostfixMalik { public static void main(String[] args) { String expression; String token; String operator; StringTokenizer tokens; int operand1, operand2, result=0; //create empty stack of pending integer operands Stack operandStack = new Stack(); expression = JOptionPane.showInputDialog( "Enter a postfix expression" ); tokens = new StringTokenizer(expression); while (tokens.hasMoreTokens()) { token = tokens.nextToken(); if (!isOperator(token)) //token is an operand (i.e. integer) //extract int from String token, create Integer object, push onto stack operandStack.push(new Integer(Integer.parseInt(token))); // printStack(operandStack); //display stack at each step. Debugging else { //token is an operator //pop two ints off stack. //convert popped Object to Integer, extract int from the Integer operand2 = ((Integer)operandStack.pop()).intValue(); operand1 = ((Integer)operandStack.pop()).intValue(); //"first" one if (token.equals("+")) result = operand1 + operand2; else if (token.equals("-")) result = operand1 - operand2; else if (token.equals("*")) result = operand1 * operand2; else if (token.equals("/")) result = operand1 / operand2; else if (token.equals("%")) result = operand1 % operand2; //push the resulting integer onto the stack operandStack.push(new Integer(result)); } } //only object in stack is the answer result = ((Integer)operandStack.pop()).intValue(); JOptionPane.showMessageDialog(null,expression+" = "+result); System.exit(0); } static boolean isOperator(String t) { if (t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/") || t.equals("%")) return true; else return false; } /* //if needed for debugging static void printStack( Stack s) { System.out.print("Stack is: "); //don't normally iterate over a stack. here for illustration purposes. Iterator items = s.iterator(); while (items.hasNext()) System.out.print(items.next()+" "); System.out.println(); } */ } /* page 399 example: 6 3 + 2 * postfix for: (6 + 3) * 2 = 18 other examples: 4 5 7 2 + - * postfix for: 4 * (5 - (7 + 2)) = -16 3 4 + 2 * 7 / postfix for: (3 + 4) * 2 / 7 = 2 5 7 + 6 2 - * postfix for: (5 + 7) * (6 - 2) = 48 4 2 + 3 5 1 - * + postfix for: 4 + 2 + 3 * (5 - 1) = 18 bonus: 2 3 + 4 * 6 4 1 - % 5 2 / - + which is the postfix for: (2+3)*4 + 6%(4-1) - 5/2 = 18 */