FileDocCategorySizeDatePackage
BigNumCalc.javaAPI DocExample1207Thu Mar 01 16:21:44 GMT 2001None

BigNumCalc

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

Fields Summary
public static Object[]
input
an array of Objects, simulating user input
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] args)


	     
		Stack s = new Stack();
		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)) {
				case '+":
					s.push(((BigDecimal)s.pop()).add((BigDecimal)s.pop()));
					break;
				case '-":
					s.push(((BigDecimal)s.pop()).subtract((BigDecimal)s.pop()));
					break;
				case '*":
					s.push(((BigDecimal)s.pop()).multiply((BigDecimal)s.pop()));
					break;
				case '/":
					s.push(((BigDecimal)s.pop()).divide((BigDecimal)s.pop(),
						BigDecimal.ROUND_UP));
					break;
				case '=":
					System.out.println(s.pop());
					break;
				default:
					throw new IllegalStateException("Unknown OPERATOR popped");
				}
			} else {
				throw new IllegalStateException("Syntax error in input");
			}
		}