【问题标题】:The character returned is not the same as stored. [closed]返回的字符与存储的字符不同。 [关闭]
【发布时间】:2014-09-19 20:50:33
【问题描述】:

当我使用中缀为 73+2* 时,字符不会以当前形式存储。它打印其他值。它应该将第一个操作数打印为 7,但会打印其他内容。

public char postfixOperation(String infix) {
    operatorStack.reset();
    int firstOperand=0;
    int secondOperand=0;
    for(int j=0;j<infix.length();j++){    // loop until the end of the line for a string (expression)
        // Check for numbers 
        if( infix.charAt(j) =='0' || infix.charAt(j) =='1' || infix.charAt(j) =='2'|| infix.charAt(j) 
        =='3'|| infix.charAt(j) =='4'|| infix.charAt(j) =='5'|| infix.charAt(j) =='6'|| infix.charAt(j) 
        =='7'|| infix.charAt(j) =='8'|| infix.charAt(j) =='9' ){
            operatorStack.push(infix.charAt(j));
                        }
        //check for '+'
        else if( infix.charAt(j)=='+'){
            firstOperand = operatorStack.pop(); // pop first operand
            System.out.println(firstOperand);
            secondOperand = (int) operatorStack.pop(); // pop second operand
            operatorStack.push((char) (firstOperand + secondOperand));
        }
        //check for '-'


       else if( infix.charAt(j)=='-'){
            firstOperand = (int) operatorStack.pop();   // pop first operand
            secondOperand = (int) operatorStack.pop(); // pop second operand
            operatorStack.push((char) (firstOperand - secondOperand));
        }
        //check for '*'
        else if( infix.charAt(j)=='*'){
            firstOperand = (int) operatorStack.pop();   // pop first operand
            secondOperand = (int) operatorStack.pop(); // pop second operand
            operatorStack.push((char) (firstOperand * secondOperand));
        }
        //check for '/'
        else if( infix.charAt(j)=='/'){
            firstOperand = (int) operatorStack.pop();   // pop first operand
            secondOperand = (int) operatorStack.pop(); // pop second operand
            operatorStack.push((char) (firstOperand / secondOperand));
        }

    }        
    return operatorStack.pop();
}

【问题讨论】:

  • 您似乎在要求我们为您调试代码。
  • but something else is printed - 那可能是什么?
  • 我认为您需要更改运算符堆栈以包含字符串,并且在确定已传递整个数字之前不要从等式中删除数字。此外,您正在将chars 加载到您的堆栈中,并将它们作为ints 拉出;我很确定 (int)'1' 在 Java 中等于 49。
  • 我有一个 77*2- 的字符串,我怎样才能分解成整数并处理它?
  • 我在pastebin.com/YZjWkVU6创建了一个解析方程的例子

标签: java char stack


【解决方案1】:

您继续使用char 变量并对其数值执行操作。例如,这意味着'9' - '7' == 2,而不是'2'。相反,请从您的输入字符中减去 '0' 并改用数值。

【讨论】:

  • 好的,那么可以做些什么呢?我是 Java 新手
猜你喜欢
  • 2020-10-10
  • 2012-09-11
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
  • 1970-01-01
相关资源
最近更新 更多