我对我应该评估前缀表达式的方法有疑问。我已经让它用于使用堆栈的post fix表达式,所以我认为它应该是类似的。我需要从右到左阅读而不是从左到右阅读。这是我的评估方法,任何建议或指示将不胜感激:
// evaluates a preFix expression
public static int evaluate(String input)
{
int number, leftOperand, rightOperand, result;
char operator;
String token;
// create an integer stack
Stack<Integer> stack = new Stack<Integer>();
// create string tokenizer containing string input
StringTokenizer tokenizer = new StringTokenizer(input);
// while input string has more tokens
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();// get next token
// if token is character
if (isChar(token)) {
number = Integer.parseInt(token);// push into stack
stack.push(number);
// if token is operator
} else {
operator = token.charAt(0);// get operator
rightOperand = stack.pop();// pop two numbers
leftOperand = stack.pop();
result = evaluate(rightOperand, leftOperand, operator);// evaluate
stack.push(result);// push result
}
}
return stack.pop();// final answer
例外:
Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:572)
at java.lang.Integer.parseInt(Integer.java:615)
at PrefixEvaluator.evaluate(PrefixEvaluator.java:40)
at PrefixEvaluator.main(PrefixEvaluator.java:99)
答案 0 :(得分:0)
NumberFormatException
表示您试图解析&#39; - &#39;作为一个数字。因此,您发布的代码必定存在问题,以确定代币是数字还是运算符。