write a program to evaluate the value of the infix expression consisting of operator

6
Write a program to evaluate the value of the infix expression consisting of operator, operands and parentheses Solution Introduction Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression. Algorithm 1. The first step is breaking up the input into a sequence of tokens, where each token represents an arithmetic operation, a number, or parentheses. 2. Find the next token, skipping blanks, and return it. 3. Print error message if input is unrecognized. 4. Skip blanks 5. Scan the tokens from left to right ignoring everything but open parenthesis and close parenthesis tokens. 6. Whenever you encounter an open parenthesis token, push it on the stack. 7. Whenever you encounter a close parenthesis token, pop the stack. If the stack is empty, output an error message. 8. When you have read all the tokens, check to see whether or not the stack is empty. If the stack is empty, declare success. If the stack still has something on it you have an unbalanced open parenthesis in your expression. 9. Process the current token

Upload: megha-gupta

Post on 22-Feb-2015

112 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Write a Program to Evaluate the Value of the Infix Expression Consisting of Operator

Write a program to evaluate the value of the infix expression consisting of operator, operands and parentheses

Solution

Introduction

Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression.

Algorithm

1. The first step is breaking up the input into a sequence of tokens, where each token represents an arithmetic operation, a number, or parentheses.

2. Find the next token, skipping blanks, and return it.3. Print error message if input is unrecognized.4. Skip blanks5. Scan the tokens from left to right ignoring everything but open parenthesis

and close parenthesis tokens.6. Whenever you encounter an open parenthesis token, push it on the stack.7. Whenever you encounter a close parenthesis token, pop the stack. If the

stack is empty, output an error message.8. When you have read all the tokens, check to see whether or not the stack is

empty. If the stack is empty, declare success. If the stack still has something on it you have an unbalanced open parenthesis in your expression.

9. Process the current token

Page 2: Write a Program to Evaluate the Value of the Infix Expression Consisting of Operator

Code in Java

import java.util.Stack;

public class InfixPostfixEvaluator {

        /**         * Operators in reverse order of precedence.         */        private static final String operators = "-+/*";        private static final String operands = "0123456789";

        public int evalInfix(String infix) {                return evaluatePostfix(convert2Postfix(infix));        }

        public String convert2Postfix(String infixExpr) {                char[] chars = infixExpr.toCharArray();                Stack<Character> stack = new Stack<Character>();                StringBuilder out = new StringBuilder(infixExpr.length());

                for (char c : chars) {                        if (isOperator(c)) {                                while (!stack.isEmpty() && stack.peek() != '(') {                                        if (operatorGreaterOrEqual(stack.peek(), c)) {                                                out.append(stack.pop());                                        } else {                                                break;                                        }                                }                                stack.push(c);                        } else if (c == '(') {                                stack.push(c);                        } else if (c == ')') {

Page 3: Write a Program to Evaluate the Value of the Infix Expression Consisting of Operator

                                while (!stack.isEmpty() && stack.peek() != '(') {                                        out.append(stack.pop());                                }                                if (!stack.isEmpty()) {                                        stack.pop();                                }                        } else if (isOperand(c)) {                                out.append(c);                        }                }                while (!stack.empty()) {                        out.append(stack.pop());                }                return out.toString();        }

        public int evaluatePostfix(String postfixExpr) {                char[] chars = postfixExpr.toCharArray();                Stack<Integer> stack = new Stack<Integer>();                for (char c : chars) {                        if (isOperand(c)) {                                stack.push(c - '0'); // convert char to int val                        } else if (isOperator(c)) {                                int op1 = stack.pop();                                int op2 = stack.pop();                                int result;                                switch (c) {                                case '*':                                        result = op1 * op2;                                        stack.push(result);                                        break;                                case '/':                                        result = op2 / op1;                                        stack.push(result);

Page 4: Write a Program to Evaluate the Value of the Infix Expression Consisting of Operator

                                        break;                                case '+':                                        result = op1 + op2;                                        stack.push(result);                                        break;                                case '-':                                        result = op2 - op1;                                        stack.push(result);                                        break;                                }                        }                }                return stack.pop();        }        private int getPrecedence(char operator) {                int ret = 0;                if (operator == '-' || operator == '+') {                        ret = 1;                } else if (operator == '*' || operator == '/') {                        ret = 2;                }                return ret;        }        private boolean operatorGreaterOrEqual(char op1, char op2) {                return getPrecedence(op1) >= getPrecedence(op2);        }

        private boolean isOperator(char val) {                return operators.indexOf(val) >= 0;        }

        private boolean isOperand(char val) {                return operands.indexOf(val) >= 0;        }

Page 5: Write a Program to Evaluate the Value of the Infix Expression Consisting of Operator

}