public class PrelimCalculator
1: //PrelimCalculator.java
2:
3: import java.util.*;
4:
5: /**
6: PRELIMINARY VERSION without exception handling.
7: Simple line-oriented calculator program. The class
8: can also be used to create other calculator programs.
9: */
10: public class PrelimCalculator
11: {
12: private double result;
13: private double precision = 0.0001;
14: //Numbers this close to zero are treated as if equal to zero.
15: public static void main(String[] args)
16: throws DivideByZeroException,
17: UnknownOpException
18: {
19: PrelimCalculator clerk = new PrelimCalculator( );
20: System.out.println("Calculator is on.");
21: System.out.print("Format of each line: ");
22: System.out.println("operator space number");
23: System.out.println("For example: + 3");
24: System.out.println("To end, enter the letter e.");
25: clerk.doCalculation( );
26: System.out.println("The final result is "
27: + clerk.resultValue( ));
28: System.out.println("Calculator program ending.");
29: }
30: public PrelimCalculator( )
31: {
32: result = 0;
33: }
34: public void reset( )
35: {
36: result = 0;
37: }
38:
39: public void setResult(double newResult)
40: {
41: result = newResult;
42: }
43: public double resultValue( )
44: {
45: return result;
46: }
47: /**
48: Returns n1 op n2, provided op is one of '+', '–', '*',or '/'.
49: Any other value of op throws UnknownOpException.
50: */
51: public double evaluate(char op, double n1, double n2)
52: throws DivideByZeroException, UnknownOpException
53: {
54: double answer;
55: switch (op)
56: {
57: case '+':
58: answer = n1 + n2;
59: break;
60: case '-':
61: answer = n1 - n2;
62: break;
63: case '*':
64: answer = n1 * n2;
65: break;
66: case '/':
67: if ( (-precision < n2) && (n2 < precision))
68: throw new DivideByZeroException( );
69: answer = n1/n2;
70: break;
71: default:
72: throw new UnknownOpException(op);
73: }
74: return answer;
75: }
76:
77: public void doCalculation( ) throws DivideByZeroException,
78: UnknownOpException
79: {
80: char nextOp;
81: double nextNumber;
82: boolean done = false;
83: Scanner keyboard = new Scanner(System.in);
84: result = 0;
85: System.out.println("result = " + result);
86:
87: while (! done)
88: {
89: nextOp = (keyboard.next( )).charAt(0);
90: if ((nextOp == 'e') || (nextOp == 'E'))
91: done = true;
92: else
93: {
94: nextNumber = keyboard.nextDouble( );
95: result = evaluate(nextOp, result, nextNumber);
96: System.out.println("result " + nextOp + " "
97: + nextNumber + " = " + result);
98: System.out.println("updated result = " + result);
99: }
100: }
101: }
102: }
103:
104:
105:
106: