【发布时间】: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创建了一个解析方程的例子