当我使用中缀为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();
}
答案 0 :(得分:2)
您继续使用char
变量并对其数值执行操作。这意味着,例如,'9' - '7' == 2
,而不是'2'
。而是从输入字符中减去'0'
并改为使用数值。