public class PrelimCalculator
1:
2: import java.util.Scanner;
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; // Numbers this close to zero are
13: // treated as if equal to zero.
14:
15: public static void main(String[] args) 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:
26: System.out.println("The final result is " +
27: clerk.getResult( ));
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 getResult( )
44: {
45: return result;
46: }
47:
48: public void doCalculation( ) throws DivideByZeroException,
49: UnknownOpException
50: {
51: Scanner keyboard = new Scanner(System.in);
52: boolean done = false;
53: result = 0;
54: System.out.println("result = " + result);
55:
56: while (!done)
57: {
58: char nextOp = (keyboard.next( )).charAt(0);
59: if ((nextOp == 'e') || (nextOp == 'E'))
60: done = true;
61: else
62: {
63: double nextNumber = keyboard.nextDouble( );
64: result = evaluate(nextOp, result, nextNumber);
65: System.out.println("result " + nextOp + " " +
66: nextNumber + " = " + result);
67: System.out.println("updated result = " + result);
68: }
69: }
70: }
71:
72: /**
73: Returns n1 op n2, provided op is one of '+', '-', '*',or '/'.
74: Any other value of op throws UnknownOpException.
75: */
76: public double evaluate(char op, double n1, double n2)
77: throws DivideByZeroException, UnknownOpException
78: {
79: double answer;
80: switch (op)
81: {
82: case '+':
83: answer = n1 + n2;
84: break;
85: case '-':
86: answer = n1 - n2;
87: break;
88: case '*':
89: answer = n1 * n2;
90: break;
91: case '/':
92: if ((-precision < n2) && (n2 < precision))
93: throw new DivideByZeroException( );
94: answer = n1 / n2;
95: break;
96: default:
97: throw new UnknownOpException(op);
98: }
99: return answer;
100: }
101: }
102:
103:
104:
105: