我被指示有一个计算后缀表达式的方法。我得到一个输出,但我得到的输出是错误的数字。
static final char addition = '+', subtraction ='-', multiply = '*', divide = '/';
@SuppressWarnings({ "rawtypes", "unchecked" })
public static boolean evaluatePostfix(String lines, boolean check){
if (check = false) {
return false;
}
Stack expression = new Stack();
String token;
StringTokenizer tokenizer = new StringTokenizer(lines, " ");
int operator1 = 0, operator2 = 0, result = 0;
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken(" ");
if(token == " ") {
System.out.print("");
} else if (isOperator(token)) {
operator2 = ((Integer) expression.pop()).intValue();
operator1 = ((Integer) expression.pop()).intValue();
result = evaluateOperator(token.charAt(0), operator1, operator2);
expression.push(new Integer(result));
} else {
expression.push((Integer.parseInt(token)));
}
}
System.out.println("The result of the expression is: " + result);
return check = true;
}
//Checks expression from parameters passed through and evaluates
private static int evaluateOperator(char charAt, int operator1, int operator2) {
int result = 0;
switch(charAt) {
case addition:
result = operator1 + operator2;
System.out.println(result);
case subtraction:
result = operator1 - operator2;
System.out.println(result);
case multiply:
result = operator1 * operator2;
System.out.println(result);
//case divide:
//result = operator1 / operator2;
}
return result;
}
//Checks whether operator is *,/,+,-. Returns true or false.
public static boolean isOperator(char token) {
switch(token) {
case "-": case "/": case "+": case "*":
return true;
default:
return false;
}
}
-
这是我得到的输出。正如您所看到的,计算开始正确,但随后进入纳尼亚。我无法弄清楚为什么。