到目前为止,这是我的代码:
public class PostfixCalculator {
private Stack<Float> stack;
private float result;
private Boolean isOperator (char op){
boolean operator;
switch (op){
case '+':
case '-':
case '*':
case '/':
case '^':
operator = true;
break;
default:
operator = false;
break;}
return operator;
}
private Boolean isFunction (String func){
String[] functions = {"sin", "cos", "max"};
for (int i=0; i<functions.length; i++){
if (func.equals(functions[i]))
return true; }
return false;
}
private void computeOperator (float op1, float op2, char op){
switch (op){
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '/':
result = op1/op2;
break;
case '*':
result = op1 * op2;
break;
case '^':
result = (float) Math.pow(op1, op2);
break;
default:
break;
}
}
public float calculate(String expr) throws IllegalArgumentException {
result = 0;
String token;
Float makeit;
char operator;
float op1, op2, pushFloat;
StringTokenizer calc=new StringTokenizer(expr);
stack = new Stack<Float>();
while (calc.hasNextToken()){
token=calc.getNextToken();
operator=token.charAt(0);
if (!(this.isOperator(operator))){
if (this.isFunction(token)){
if (token.equals("sin")){
op1=stack.pop();
result = (float) Math.sin(op1);
stack.push(result);
}
else if (token.equals("cos")){
op1=stack.pop();
result = (float) Math.cos(op1);
stack.push(result);
}
else if (token.equals("max")){
op1=stack.pop();
op2=stack.pop();
result=Math.max(op1, op2);
stack.push(result);
}
}
else {
makeit = new Float(token);
pushFloat = makeit.floatValue();
stack.push(pushFloat);
}
}
else {
op1 = stack.pop();
op2 = stack.pop();
computeOperator (op1, op2, operator);
stack.push(result);
}
}
return stack.pop();
}
}
我想我已经掌握了它的基础知识,但是如何处理连续三位或更多位数的后缀计算,例如'2 3 4 * -'?任何帮助,将不胜感激。提前致谢!