如何在算术方程中对多个指数进行优先级排序^

时间:2013-10-29 18:32:27

标签: java math postfix-notation infix-notation exponential

我正在研究一种解决算术方程的程序。我遇到一个问题,当程序没有正确解决它们的行中有多个指数语句时发生。一个例子是:2 ^ 3 ^ 2,正确的答案是512但是程序输出64.这是因为程序执行2 ^ 3然后是8 ^ 2,而不是执行3 ^ 2然后执行2 ^ 9。如果您对如何修改当前代码或添加内容有任何想法,请与我们联系。

import java.text.DecimalFormat;
import java.util.EmptyStackException;
import myUtil.*;

public class PostFixEvaluator extends Asg6
{
    public static class SyntaxErrorException extends Exception
    {
        SyntaxErrorException(String message)
        {
            super(message);
        }
    }

    private static final String operators = "+-*/^()";
    private AStack<Double> operandStack;

    private double evaluateOP(char op) throws Exception
    {
        double rightside = operandStack.pop();
        double leftside = operandStack.pop();
        double result = 0;
        if(op == '+')
        {
            result = leftside + rightside;
        }
        else if(op == '-')
        {
            result = leftside - rightside;
        }
        else if(op == '*')
        {
            result = leftside * rightside;
        }
        else if(op == '/')
        {
            if(rightside == 0)
            {
                throw new Exception("Can not divide by 0, the equation is undefined");
            }
            else
            {
                result = leftside / rightside;
            }
        }
        else if(op == '^')
        {
            result = Math.pow(leftside, rightside);
        }
        return result;
    }

    private boolean isOperator(char ch)
    {
        return operators.indexOf(ch) != -1;
    }

    public double evaluate(String exp) throws Exception
    {
        operandStack = new AStack<Double>();
        String[] tokens = exp.split("\\s+");
        try
        {
            for(String nextToken : tokens)
            {
                char firstChar = nextToken.charAt(0);
                if(Character.isDigit(firstChar))
                {
                    double value = Double.parseDouble(nextToken);
                    operandStack.push(value);
                }
                else if (isOperator(firstChar))
                {
                    double result = evaluateOP(firstChar);
                    operandStack.push(result);
                }
                else
                {
                    throw new Exception("Invalid character: " + firstChar);
                }
            }
            double answer = operandStack.pop();
            if(operandStack.empty())
            {
                return answer;
            }
            else
            {
                throw new Exception("Syntax Error: Stack should be empty");
            }
        }
        catch(EmptyStackException ex)
        {
            throw new Exception("Syntax Error: The stack is empty");
        }
    }

}

2 个答案:

答案 0 :(得分:0)

您正在尝试使用 LL(1)语法(这是递归下降解析器可以解析的)来建模右关联运算符(^)。右关联运算符需要左递归,这对于 LL(1)语法来说并不容易。您需要查看左分解:http://en.wikipedia.org/wiki/LL_parser#Left_Factoring

答案 1 :(得分:0)

我会用操作符优先级来解决这个问题,因为你可能还想拥有它们。 为了测试我改变了类,所以我可以测试它,它肯定不是最有效或可读但你应该得到 这个想法是如何运作的。

import java.text.DecimalFormat;
import java.util.EmptyStackException;

import java.util.*;

public class PostFixEvaluator
{
    public static class SyntaxErrorException extends Exception
    {
        SyntaxErrorException(String message)
        {
            super(message);
        }
    }

    private static final String operators = "+-*/^()";
    private static int[] operatorPriority = {1,1,2,2,3,10,10};
    private Stack<Double> operandStack;
    private Stack<Character> operatorStack;

    private double evaluateOP(char op) throws Exception
    {
        double rightside = operandStack.pop();
        double leftside = operandStack.pop();
        double result = 0;
        if(op == '+')
        {
            result = leftside + rightside;
        }
        else if(op == '-')
        {
            result = leftside - rightside;
        }
        else if(op == '*')
        {
            result = leftside * rightside;
        }
        else if(op == '/')
        {
            if(rightside == 0)
            {
                throw new Exception("Can not divide by 0, the equation is undefined");
            }
            else
            {
                result = leftside / rightside;
            }
        }
        else if(op == '^')
        {
            result = Math.pow(leftside, rightside);
        }
        return result;
    }

    private boolean isOperator(char ch)
    {
        return operators.indexOf(ch) != -1;
    }

    public double evaluate(String exp) throws Exception
    {
        operandStack = new Stack<Double>();
        operatorStack = new Stack<Character>();
        String[] tokens = exp.split("\\s+");
        try
        {
            for(String nextToken : tokens)
            {
                char firstChar = nextToken.charAt(0);
                if(Character.isDigit(firstChar))
                {
                    double value = Double.parseDouble(nextToken);
                    operandStack.push(value);
                }
                else if (isOperator(firstChar))
                {
                    // Try to evaluate the operators on the stack
                    while (!operatorStack.isEmpty())
                    {
                        char tmpOperator = operatorStack.pop();
                        // If Operator has higher Priority than the one before,
                        // Calculate it first if equal first calculate the second
                        // operator to get the ^ problem fixed
                        if (operatorPriority[operators.indexOf(firstChar)] >= operatorPriority[operators.indexOf(tmpOperator)])
                        {
                           operatorStack.push(tmpOperator);
                           // Operand has to be fetched first
                           break;
                        }
                        else
                        {
                            double result = evaluateOP(tmpOperator);
                            operandStack.push(result);
                        }
                    }
                    operatorStack.push(firstChar);
                }
                else
                {
                    throw new Exception("Invalid character: " + firstChar);
                }
            }

            // Here we need to calculate the operators left on the stack
            while (!operatorStack.isEmpty())
            {
                char tmpOperator = operatorStack.pop();
                // Operator Priority has to be descending,
                // or the code before is wrong.
                double result = evaluateOP(tmpOperator);
                operandStack.push(result);
            }

            double answer = operandStack.pop();
            if(operandStack.empty())
            {
                return answer;
            }
            else
            {
                throw new Exception("Syntax Error: Stack should be empty");
            }
        }
        catch(EmptyStackException ex)
        {
            throw new Exception("Syntax Error: The stack is empty");
        }
    }

    // For testing Only
    public static void main(String[] args) throws Exception
    {
        PostFixEvaluator e = new PostFixEvaluator();
        System.out.println(e.evaluate("2 ^ 3 ^ 2"));
    }

}