UNB/ CS/ David Bremner/ teaching/ java/ RPNStack2.java
import java.math.BigDecimal;
import java.lang.UnsupportedOperationException;
public class RPNStack2 {
    private int scale=10;

    private VecStack stack=new VecStack();

    public void process (String arg)
        throws EmptyStackException, NumberFormatException,
               ArithmeticException{

        if (isBinaryOperator(arg)){
            if (stack.size() < 2){
                throw new EmptyStackException("Not enough operands");
            }
            BigDecimal right=pop();
            BigDecimal left=pop();

            push(eval(arg,left,right));
        } else {
            BigDecimal num=new BigDecimal(arg);
            push(num);
        }
    }

    public BigDecimal pop(){
        return (BigDecimal)stack.pop();
    }

    public BigDecimal top(){
        return (BigDecimal)stack.top();
    }

    public void push(BigDecimal num){
        stack.push(num);
    }

    public void push(String str){
        stack.push(new BigDecimal(str));
    }


    
    private BigDecimal eval (String op,BigDecimal l,  BigDecimal r)
                throws UnsupportedOperationException{
        BigDecimal result;
        
        switch(op.charAt(0)){
        case '+':
            result=l.add(r);
            break;
        case '-':
            result=l.subtract(r);
            break;
        case '*':
            result=l.multiply(r);
            break;
        case '/':
            if (r.signum()==0)
                throw new DivideByZeroException();

            result=l.divide(r,this.scale,BigDecimal.ROUND_HALF_UP);
            break;
        default:
            throw new UnsupportedOperationException(op);
        }
        return result;
    }


    private boolean isBinaryOperator(String text){
        if (text.length()>1)
            return false;
        switch(text.charAt(0)){
        case '+':
        case '-':
        case '*':
        case '/':
            return true;
        default:
            return false;
        }
    }
}
//