0

我正在开发一个解决算术方程的程序。我遇到了一个问题,当程序没有正确解决它们时,一行中有多个指数语句。例如: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");
        }
    }

}
4

2 回答 2

0

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

于 2013-10-29T20:23:05.363 回答
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"));
    }

}
于 2013-10-29T20:23:18.037 回答