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