// start of code: copy and paste into a new project and run...
// Code adapted from Oages 173-175 of Kauffman & Wolfgang text...
//
import java.util.EmptyStackException;
import java.util.Stack;
import javax.swing.JOptionPane;
public class PostfixEvaluator {
private static final String OPERATORS = "+-*/";
private Stack<Integer> operandStack;
private int evalOp(char op) {
int rhs = operandStack.pop();
int lhs = operandStack.pop();
int result = 0;
// Evaluate the operator
switch (op) {
case '+' : result = lhs + rhs;
break;
case '-' : result = lhs - rhs;
break;
case '/' : result = lhs / rhs;
break;
case '*' : result = lhs * rhs;
break;
}
return result;
}
private boolean isOperator(char ch) {
return OPERATORS.indexOf(ch) != -1;
}
public int eval(String expression) throws SyntaxErrorException {
// Create an empty stack
operandStack = new Stack<Integer>();
// Process each token
String[] tokens = expression.split("\\s+");
try {
for (String nextToken : tokens) {
char firstChar = nextToken.charAt(0);
// Does it start with a digit?
if (Character.isDigit(firstChar)) {
// Get the integer value
int value = Integer.parseInt(nextToken);
// Push value onto operand stack
operandStack.push(value);
} // Is it an operator?
else if (isOperator(firstChar)) {
// Evaluate the operator
int result = evalOp(firstChar);
// Push result onto the operand stack
operandStack.push(result);
}
else {
// Invalid character
throw new SyntaxErrorException("Invalid character encountered:" + firstChar);
}
}
// NO more tokens - pop result from operand stack.
int answer = operandStack.pop();
// Operand stack should be empty
if (operandStack.empty()) {
return answer;
}
else {
// Indicate syntax error
throw new SyntaxErrorException("Syntax error: Stack should be empty.");
}
} catch (EmptyStackException ex) {
// Pop was atempted on an empty stack
throw new SyntaxErrorException("Syntax Error: The stack is empty.");
}
}
public static class SyntaxErrorException extends Exception {
SyntaxErrorException(String message) {
super(message);
}
}
// A test driver for evaluating postfix expressions...
public static void main(String[] args) {
String[] choices = { "Again", "Done" };
int response = 0;
PostfixEvaluator c = new PostfixEvaluator();
do {
String exp = JOptionPane.showInputDialog("Enter a postfix expression:");
System.out.println("Evaluating expression:" + exp);
try {
int r = c.eval(exp);
System.out.println("Result of evaluating " + exp + " is " + r);
response = JOptionPane.showOptionDialog(null,
"The expression: " + exp + " evaluates to " + c.eval(exp), "Results",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);
} catch (SyntaxErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
} while (response==0);
}
}
// end of code--------