下面我有评估前缀表达式的代码。我首先将表达式读入允许我从右到左读取的 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");
}
}