FileDocCategorySizeDatePackage
SimpleCalcStreamTok.javaAPI DocExample2856Wed Mar 10 12:22:26 GMT 2004None

SimpleCalcStreamTok

public class SimpleCalcStreamTok extends Object
SimpleCalc -- simple calculator to show StringTokenizer
author
Ian Darwin, http://www.darwinsys.com/
version
$Id: SimpleCalcStreamTok.java,v 1.10 2004/03/10 18:22:26 ian Exp $

Fields Summary
protected StreamTokenizer
tf
The StreamTokenizer Input
protected PrintWriter
out
The Output File
protected String
variable
The variable name (not used in this version)
protected Stack
s
The operand stack
Constructors Summary
public SimpleCalcStreamTok(String fileName)
Construct by filename

		this(new FileReader(fileName));
	
public SimpleCalcStreamTok(Reader rdr)
Construct 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();
	
public SimpleCalcStreamTok(Reader in, PrintWriter out)
Construct from a Reader and a PrintWriter

		this(in);
		setOutput(out);
	
Methods Summary
voidclearStack()

		s.removeAllElements();
	
protected voiddoCalc()

		int iType;
		double tmp;

		while ((iType = tf.nextToken()) != StreamTokenizer.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 '+":
				// + operator is commutative.
				push(pop() + pop());
				break;
			case '-":
				// - operator: order matters.
				tmp = pop();
				push(pop() - tmp);
				break;
			case '*":
				// Multiply is commutative
				push(pop() * pop());
				break;
			case '/":
				// Handle division carefully: order matters!
				tmp = pop();
				push(pop() / tmp);
				break;
			case '=":
				out.println(peek());
				break;
			default:
				out.println("What's this? iType = " + iType);
			}
		}
	
public static voidmain(java.lang.String[] av)


	/* Driver - main program */
	       
		if (av.length == 0)
			new SimpleCalcStreamTok(
				new InputStreamReader(System.in)).doCalc();
		else 
			for (int i=0; i<av.length; i++)
				new SimpleCalcStreamTok(av[i]).doCalc();
	
doublepeek()

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

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

		s.push(new Double(val));
	
public voidsetOutput(java.io.PrintWriter out)
Change the output destination.

		this.out = out;