FileDocCategorySizeDatePackage
SimpleCalc.javaAPI DocExample2342Sat Oct 27 15:57:18 BST 2001None

SimpleCalc

public class SimpleCalc extends Object
SimpleCalc -- simple calculator to show StringTokenizer
author
Ian Darwin, ian@darwinsys.com
version
$Id: SimpleCalc.java,v 1.4 2001/10/27 18:57:18 ian Exp $

Fields Summary
protected StreamTokenizer
tf
The StreamTokenizer
protected String
variable
The variable name (not used in this version)
protected Stack
s
The operand stack
Constructors Summary
public SimpleCalc(String fileName)
Construct a SimpleCalc by name

		this(new FileReader(fileName));
	
public SimpleCalc(Reader rdr)
Construct a SimpleCalc from an existing Reader

		tf = new StreamTokenizer(rdr);
		// Control the input character set:
		tf.slashSlashComments(true);	// treat "//" as comments
		tf.ordinaryChar('-");		// used for subtraction
		tf.ordinaryChar('/");	// used for division

		s = new Stack();
	
Methods Summary
voidclearStack()

		s.removeAllElements();
	
protected voiddoCalc()

		int iType;
		double tmp;

		while ((iType = tf.nextToken()) != tf.TT_EOF) {
			switch(iType) {
			case StreamTokenizer.TT_NUMBER: // Found a number, push value to stack
				push(tf.nval);
				break;
			case StreamTokenizer.TT_WORD:
				// Found a variable, save its name. Not used here. */
				variable = tf.sval;
				break;
			case '+":
				// Found + operator, perform it immediately.
				push(pop() + pop());
				break;
			case '-":
				// Found + operator, perform it (order matters).
				tmp = pop();
				push(pop() - tmp);
				break;
			case '*":
				// Multiply works OK
				push(pop() * pop());
				break;
			case '/":
				// Handle division carefully: order matters!
				tmp = pop();
				push(pop() / tmp);
				break;
			case '=":
				System.out.println(peek());
				break;
			default:
				System.out.println("What's this? iType = " + iType);
			}
		}
	
public static voidmain(java.lang.String[] av)

		if (av.length == 0)
			new SimpleCalc(
				new InputStreamReader(System.in)).doCalc();
		else 
			for (int i=0; i<av.length; i++)
				new SimpleCalc(av[i]).doCalc();
	
doublepeek()

		return ((Double)s.peek()).doubleValue();
	
doublepop()

		return ((Double)s.pop()).doubleValue();
	
voidpush(double val)

		s.push(new Double(val));