FileDocCategorySizeDatePackage
SimpleCalcScanner.javaAPI DocExample2738Wed Mar 10 12:01:36 GMT 2004None

SimpleCalcScanner

public class SimpleCalcScanner extends Object
SimpleCalc -- simple calculator using 1.5 java.util.Scanner
version
$Id: SimpleCalcScanner.java,v 1.3 2004/03/10 18:01:35 ian Exp $

Fields Summary
protected Scanner
scan
The Scanner
protected PrintWriter
out
The output
protected String
variable
The variable name (not used in this version)
protected Stack
s
The operand stack
Constructors Summary
public SimpleCalcScanner(String fileName)
Construct a SimpleCalcScanner by name

		this(new FileReader(fileName));
	
public SimpleCalcScanner(Reader rdr)
Construct a SimpleCalcScanner from an open Reader

		scan = new Scanner(rdr);
		// Control the input character set:
		scan.slashSlashComments(true);	// treat "//" as comments
		scan.ordinaryChar('-");		// used for subtraction
		scan.ordinaryChar('/");	// used for division
	
public SimpleCalcScanner(Reader rdr, PrintWriter pw)
Construct a SimpleCalcScanner from a Reader and a PrintWriter

		this(rdr);
		setWriter(pw);
	
Methods Summary
voidclearStack()

		s.removeAllElements();
	
protected voiddoCalc()

		int iType;
		double tmp;

		while (scan.hasNext()) {
			if (scan.hasNextDouble()) {
				push(scan.nextDouble());
			} else {
				String token = scan.next().toString();
				if (token.equals("+")) {
					// Found + operator, perform it immediately.
					push(pop() + pop());
				} else if (token.equals("-")) {
					// Found - operator, perform it (order matters).
					tmp = pop();
					push(pop() - tmp);
				} else if (token.equals("*")) {
					// Multiply is commutative
					push(pop() * pop());
				} else if (token.equals("/")) {
					// Handle division carefully: order matters!
					tmp = pop();
					push(pop() / tmp);
				} else if (token.equals("=")) {
					out.println(peek());
				} else {
					out.println("What's this? " + token);
				}
			}
		}
	
public static voidmain(java.lang.String[] av)


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

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

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

		s.push(new Double(val));
	
public voidsetWriter(java.io.PrintWriter pw)
Change the output to go to a new PrintWriter

		out = pw;