-2
當我將中綴用作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();
}
看起來好像您要求我們爲您調試代碼。 – 2014-09-19 20:53:36
'但是別的東西被打印出來了 - - 那還有什麼可能呢? – azurefrog 2014-09-19 20:57:32
我認爲您需要更改您的運算符堆棧以包含字符串,並且在您確定您已經通過了整個數字之前,不要從等式中刪除一個數字。此外,你正在將'char'加載到你的堆棧中,並將它們作爲int來加載;我很確定'(int)'1''等於49。 – mstrthealias 2014-09-19 21:01:08