后缀计算器产生错误的值

时间:2015-05-06 20:10:43

标签: java int

在java中,我试图用后缀表示法计算东西。但是,当我放入任何内容时,它使用ancii值而不是int来计算它们。所以我的所有价值观都错了。这只是计算器代码段。我在操作数和结尾处有相同的代码,但操作数在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()

1 个答案:

答案 0 :(得分:0)

零的ASCII(非ANCII)值为48 您似乎正在将数字的ASCII码推送到堆栈中。 因此,要么减去48,要么使用Integer.parseInt(ch)。