0

下面我有评估前缀表达式的代码。我首先将表达式读入允许我从右到左读取的 inputArray,然后使用 evaluationArray 进行操作。我在这一行出现内存不足错误:evaluationStack.push(number); 我不知道为什么会这样。任何帮助将不胜感激。

导入 java.util.*;

public class PrefixEvaluator 
{
    //evaluates a prefix expression
    public static int evaluate(String input)
    {
        int number, leftOperand, rightOperand, result;
        char operator;
        String inputToken = null;

        //create input stack
        Stack<String> inputStack = new Stack<String>();
        //create an integer stack
        Stack<Integer> evaluationStack = new Stack<Integer>();


        //create string tokenizer containing input string
        StringTokenizer tokenizer = new StringTokenizer(input);

        //read string into a stack
        while (tokenizer.hasMoreTokens())
        {
            inputToken = tokenizer.nextToken(); //get next token
                inputStack.push(inputToken);   //push token     
        }


        while (inputStack.isEmpty() != true)
        {      
           //System.out.println(inputStack.pop());

            if (isNumber(inputToken))
            {
                number = Integer.parseInt(inputToken);
                evaluationStack.push(number);
            }
            else                         //if token is operator
            {
                operator = inputToken.charAt(0);   //get operator
                rightOperand = evaluationStack.pop();
                leftOperand  = evaluationStack.pop();
                result = evaluation(operator, leftOperand, rightOperand);
                evaluationStack.push(result);
            }
        }
        return evaluationStack.pop();
    }

    //tests whether token is a number
    private static boolean isNumber(String token)
    {
        char first = token.charAt(0);
        if (Character.isDigit(first))
            return true;
        else
            return false;

    }

    //perform an operation on two operands
    private static int evaluation(char operator, int leftOperand, int rightOperand)
    {
        if (operator == '+')
            return leftOperand + rightOperand;
        else if (operator == '-')
            return leftOperand - rightOperand;
        else if (operator == '*')
            return leftOperand * rightOperand;
        else if (operator == '%')
            return leftOperand % rightOperand;
        else
            return leftOperand / rightOperand;

    }


    public static void main (String [] args)
    {
        evaluate("* 4 - 165 235");
    }

}
4

1 回答 1

2

如果您在调试器中单步执行您的代码,您将看到此代码是一个无限循环。

    while (inputStack.isEmpty() != true)
    {      
       //System.out.println(inputStack.pop());

        if (isNumber(inputToken))
        {
            number = Integer.parseInt(inputToken);
            evaluationStack.push(number);

您不断测试 inputToken 并将其添加到堆栈中,但您从不更改它,因此它会一直运行,直到内存不足。

也许您打算在循环开始时使用它

       inputToken = inputStack.pop();

如果您还添加

System.out.println(evaluate("* 4 - 165 235"));

它打印

280
于 2015-02-01T21:30:20.877 回答