public class PrelimCalculator
1: //PrelimCalculator.java
2:
3: import java.util.Scanner;
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:
16: public static void main(String[] args)
17: throws DivideByZeroException, 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:
27: System.out.println("The final result is " + clerk.getResult());
28: System.out.println("Calculator program ending.");
29: }
30:
31: public PrelimCalculator()
32: {
33: result = 0;
34: }
35:
36: public void reset()
37: {
38: result = 0;
39: }
40:
41: public void setResult
42: (
43: double newResult
44: )
45: {
46: result = newResult;
47: }
48:
49: public double getResult()
50: {
51: return result;
52: }
53:
54: public void doCalculation()
55: throws DivideByZeroException, UnknownOpException
56: {
57: Scanner keyboard = new Scanner(System.in);
58: boolean done = false;
59: result = 0;
60: System.out.println("result = " + result);
61:
62: while (!done)
63: {
64: char nextOp = (keyboard.next()).charAt(0);
65: if ((nextOp == 'e') || (nextOp == 'E'))
66: done = true;
67: else
68: {
69: double nextNumber = keyboard.nextDouble();
70: result = evaluate(nextOp, result, nextNumber);
71: System.out.println("result " + nextOp + " "
72: + nextNumber + " = " + result);
73: System.out.println("updated result = " + result);
74: }
75: }
76: }
77:
78: /**
79: * Returns n1 op n2, provided op is one of '+', '-', '*',or '/'.
80: * Any other value of op throws UnknownOpException.
81: */
82: public double evaluate
83: (
84: char op,
85: double n1,
86: double n2
87: ) throws DivideByZeroException, UnknownOpException
88: {
89: double answer;
90: switch (op)
91: {
92: case '+':
93: answer = n1 + n2;
94: break;
95: case '-':
96: answer = n1 - n2;
97: break;
98: case '*':
99: answer = n1 * n2;
100: break;
101: case '/':
102: if ((-precision < n2) && (n2 < precision))
103: throw new DivideByZeroException();
104: answer = n1 / n2;
105: break;
106: default:
107: throw new UnknownOpException(op);
108: }
109: return answer;
110: }
111: }