Here is my code so far:
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();
}
}
I think I have the basics of it down, but how do I deal with postfix calculations with three digits in a row or more, like for example '2 3 4 * -'? Any help would be appreciated. Thanks in advance!
Yep, a stack. And one can implement a simple stack easily with an array and a counter -- no real need to use a fancy class.
The array would be as large as the most deeply nested expression that you can handle (10 elements should be sufficient for virtually all "real" problems).
Push is update A[i] and increment i. Pop is decrement i and reference A[i]. "8 9 +" is push(8), push(9), pop the top two elements, add them, push the result. Note that operators are never pushed, only operands/results.
'2 3 4 * -' would be push(2), push(3), push(4), pop top two, multiply, push result, pop two, subtract, push result.
"7 6 + cos" would be push(7), push(6), pop two, add, push result, pop one, perform "cos", push result.
Error if you need to pop an element and the counter is zero (eg, "7 +" -- you'd want to pop twice but you can only pop once). Also an error if the user expresses "finished" and there is more than one element in the stack.
Always "display" your top element, as that's the last value pushed or the result.