【发布时间】:2015-07-17 04:08:13
【问题描述】:
在 java 中,我试图用后缀表示法计算事物。但是,当我放入任何东西时,它会使用 ancii 值而不是 int 来计算它们。所以我所有的价值观都是错误的。这只是计算器sn-p。我对操作数和最后的结果有相同的代码,但是操作数在 ancii 中,而结果以 int 形式出现。
public int evaluate() throws IllegalStateException {
if (postfix==null) {
throw new IllegalStateException("IllegalStateException in evaluate(). Postfix expression not available yet.");
}
//valueStack is a stack of Integer objects:
StackInterface valueStack=new StackReferenceBased();
//variables for the operands:
int operand1, operand2;
//for each character ch in the string postfix
for (int i=0; i<postfix.length(); i++) {
char ch=postfix.charAt(i);
switch (ch) {
//if ch is an operator
case '+':
operand2 = (Integer) valueStack.pop();
operand1 = (Integer) valueStack.pop();
result = operand1+operand2;
valueStack.push((int) result);
break;
case '-':
operand2 = (Integer) valueStack.pop();
operand1 = (Integer) valueStack.pop();
result = operand1-operand2;
valueStack.push((int) result);
break;
case '*':
operand2 = (Integer) valueStack.pop();
operand1 = (Integer) valueStack.pop();
result = operand1*operand2;
valueStack.push((int) result);
break;
case '/':
operand2 = Integer.parseInt((String) valueStack.pop());
operand1 = Integer.parseInt((String) valueStack.pop());
result = operand1/operand2;
valueStack.push((int) result);
break;
case '%':
operand2 = Integer.parseInt((String) valueStack.pop());
operand1 = Integer.parseInt((String) valueStack.pop());
result = operand1%operand2;
valueStack.push((int) result);
break;
default: //ch is an operand
valueStack.push((int) ch);
break;
}//end of switch
}//end of for
//at the end, the value of the expression will be on the top of the stack
result=(Integer) valueStack.pop();
return result;
}//end of evaluatePostfix()
【问题讨论】:
-
“反价值”?那是什么?
antivalue = !value? -
什么是不正确的最短序列?当您在调试器中单步执行代码时,您会看到什么?为什么有些值是
Integer而有些是String?它怎么知道它是哪一个?这是否意味着要处理多于一位的数字? -
Marc B - 抱歉是指 ANCII 值。
-
Peter - Integer 和 Stirng 的铸造是试图修复它的剩余部分。没什么区别。基本上,当我尝试计算某些东西时,所有操作数都保存在 ANCII 值中,并且像这些值一样计算的是整数。所以结果是正确的,但是对于 ANCII 值而不是计算器中放入的原始整数。