Android Calculator Engine: Infix to Postfix Conversion and Evaluation

Converting Infix to Postfix Notation

The transformation of standard mathematical notation (infix) into Reverse Polish Notation (postfix) is achieved using a stack-based approach. An operator stack and a string builder for the output sequence are initialized. As the input string is processed character by character, specific rules are applied. Addition and subtraction operators trigger the popping of operators from the stack that possess equal or higher precedence. Multiplication and division operators pop only operators of the same precedence. Opening parentheses are pushed directly, while closing parentheses trigger the popping of operators until an opening parenthesis is encountered. Numeric values and decimal points are appended directly to the output. Once the string is fully traversed, any residual operators are popped from the stack to finalize the postfix sequence.

public static String buildPostfixNotation(String mathExpression) {
    Deque<String> operatorStack = new ArrayDeque<>();
    StringBuilder rpnOutput = new StringBuilder(mathExpression.length() * 2);
    int index = 0;

    while (index < mathExpression.length()) {
        char token = mathExpression.charAt(index);

        if (token == '+' || token == '-') {
            while (!operatorStack.isEmpty() && !operatorStack.peek().equals("(")) {
                rpnOutput.append(operatorStack.pop());
            }
            operatorStack.push(String.valueOf(token));
            index++;
        } else if (token == '×' || token == '÷') {
            while (!operatorStack.isEmpty() && (operatorStack.peek().equals("×") || operatorStack.peek().equals("÷"))) {
                rpnOutput.append(operatorStack.pop());
            }
            operatorStack.push(String.valueOf(token));
            index++;
        } else if (token == '(') {
            operatorStack.push(String.valueOf(token));
            index++;
        } else if (token == ')') {
            String topOperator = operatorStack.pop();
            while (topOperator != null && !topOperator.equals("(")) {
                rpnOutput.append(topOperator);
                topOperator = operatorStack.pop();
            }
            index++;
        } else {
            while (index < mathExpression.length() && ((token >= '0' && token <= '9') || token == '.')) {
                rpnOutput.append(token);
                index++;
                if (index < mathExpression.length()) {
                    token = mathExpression.charAt(index);
                }
            }
            rpnOutput.append(" ");
        }
    }

    while (!operatorStack.isEmpty()) {
        rpnOutput.append(operatorStack.pop());
    }

    return rpnOutput.toString();
}

Evaluating the Expression

The evaluation process begins by retrieving the raw mathematical expression. Unary minus signs must be normalized into binary operators to ensure correct parsing. If the expression starts with a minus, a zero is prefixed. Similarly, a zero is inserted before any minus sign immediately following an opening parenthesis. The normalized infix string is then converted to postfix notation, which is subsequently evaluated to produce a numeric result. To handle floating-point inaccuracies, the resulting double is formatted to seven decimal places. A regular expression cleans up any trailing zeros and unnecessary decimal points before the final string is returned.

public String fetchCalculatedOutput() {
    String expression = text.getText().toString();
    StringBuilder exprBuilder = new StringBuilder(expression);

    if (expression.charAt(0) == '-') {
        exprBuilder.insert(0, '0');
    }

    for (int i = 1; i < exprBuilder.length(); i++) {
        if (exprBuilder.charAt(i - 1) == '(' && exprBuilder.charAt(i) == '-') {
            exprBuilder.insert(i, '0');
        }
    }

    String normalizedExpression = exprBuilder.toString();
    String rpnString = buildPostfixNotation(normalizedExpression);
    Double computedValue = calculateRPN(rpnString);

    String formattedOutput = String.format("%.7f", computedValue);
    formattedOutput = formattedOutput.replaceAll("0+?$", "");
    formattedOutput = formattedOutput.replaceAll("[.]$", "");

    return formattedOutput;
}

Tags: Android java Calculator Reverse Polish Notation algorithm

Posted on Wed, 28 Oct 2026 16:52:30 +0000 by huzefahusain