Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package lat04;
- import java.util.Stack;
- public class PostfixEval {
- private String postfixExpression;
- private Stack<Integer> operandStack;
- public PostfixEval() {
- postfixExpression = new String();
- operandStack = new Stack<>();
- }
- public void setPostfixExp(String postfixExp) {
- postfixExpression = postfixExp;
- }
- public int evaluate(){
- for (int i = 0; i < postfixExpression.length(); i++){
- char ch = postfixExpression.charAt(i); // get the current char
- if (Character.isDigit(ch))
- operandStack.push(ch - '0'); // put integer on stack
- else if (isOperator(ch)) {
- int right = getOperand(); // pop right operand
- int left = getOperand(); // pop left operand
- int result = compute(left, right, ch);
- operandStack.push(result); // push result
- }
- else if (!Character.isWhitespace(ch)) { // other chars can be whitespace
- throw new ArithmeticException("PostfixEval: Improper char");
- }
- }
- int exprValue = ((Integer) operandStack.pop()).intValue(); // pop expr value
- if (!operandStack.isEmpty()) // stack should be empty
- throw new ArithmeticException("PostfixEval: Too many operands");
- return exprValue;
- }
- private boolean isOperator(char ch) {
- return ch == '+' || ch == '-' || ch == '*' || ch == '%' || ch == '/' || ch == '^';
- }
- private int getOperand() {
- if(operandStack.isEmpty())
- throw new ArithmeticException("PostfixEval: Too many operators");
- return operandStack.pop();
- }
- public int compute(int left, int right, char op) {
- int value = 0;
- // evaluate "left op right"
- switch (op) {
- case '+':
- value = left + right; break;
- case '-':
- value = left - right; break;
- case '*':
- value = left * right; break;
- case '^':
- value = (int)Math.pow(left, right);
- break;
- case '%':
- if (right == 0) {
- throw new ArithmeticException("PostfixEval: divide by 0");
- }
- value = left % right;
- break;
- case '/':
- if (right == 0) {
- throw new ArithmeticException("PostfixEval: divide by 0");
- }
- value = left / right;
- break;
- }
- return value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement