FileDocCategorySizeDatePackage
BigNumCalc.javaAPI DocExample1458Thu May 13 18:28:58 BST 2004None

BigNumCalc

public class BigNumCalc extends Object
A trivial reverse-polish stack-based calculator for big numbers

Fields Summary
public static Object[]
testInput
an array of Objects, simulating user input
Stack
s
Constructors Summary
Methods Summary
public java.math.BigDecimalcalculate(java.lang.Object[] input)


	    
		BigDecimal tmp;
		for (int i = 0; i < input.length; i++) {
			Object o = input[i];
			if (o instanceof BigDecimal) {
				s.push(o);
			} else if (o instanceof String) {
				switch (((String)o).charAt(0)) {
				// + and * are commutative, order doesn't matter
				case '+":
					s.push(((BigDecimal)s.pop()).add((BigDecimal)s.pop()));
					break;
				case '*":
					s.push(((BigDecimal)s.pop()).multiply((BigDecimal)s.pop()));
					break;
				// - and /, order *does* matter
				case '-":
					tmp = (BigDecimal)s.pop();
					s.push(((BigDecimal)s.pop()).subtract(tmp));
					break;
				case '/":
					tmp = (BigDecimal)s.pop();
					s.push(((BigDecimal)s.pop()).divide(tmp,
						BigDecimal.ROUND_UP));
					break;
				default:
					throw new IllegalStateException("Unknown OPERATOR popped");
				}
			} else {
				throw new IllegalArgumentException("Syntax error in input");
			}
		}
		return (BigDecimal)s.pop();
	
public static voidmain(java.lang.String[] args)


	     
		BigNumCalc calc = new BigNumCalc();
		System.out.println(calc.calculate(testInput));