下面我有用于评估前缀表达式的代码。我首先将表达式读入inputArray,它允许我从右到左阅读,然后使用evaluateArray进行操作。我在此行中出现内存错误:evaluationStack.push(number); 我不知道为什么会这样。任何帮助将不胜感激。
import 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");
}
}
答案 0 :(得分: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