-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculatorEngine.java
More file actions
292 lines (250 loc) · 9.2 KB
/
CalculatorEngine.java
File metadata and controls
292 lines (250 loc) · 9.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package com.calchunter;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public final class CalculatorEngine {
private static final MathContext DIVISION_CONTEXT = new MathContext(16, RoundingMode.HALF_UP);
private static final MathContext SCIENTIFIC_CONTEXT = new MathContext(14, RoundingMode.HALF_UP);
private BigDecimal storedValue;
private String pendingOperator;
private boolean startNewInput = true;
private boolean showingError;
private String displayText = "0";
private String expressionText = " ";
public String inputDigit(String digit) {
clearErrorIfNeeded();
if (startNewInput) {
displayText = digit;
startNewInput = false;
updateExpressionWithCurrentValue();
return displayText;
}
if ("0".equals(displayText)) {
displayText = digit;
} else {
displayText += digit;
}
updateExpressionWithCurrentValue();
return displayText;
}
public String inputDecimal() {
clearErrorIfNeeded();
if (startNewInput) {
displayText = "0.";
startNewInput = false;
updateExpressionWithCurrentValue();
return displayText;
}
if (!displayText.contains(".")) {
displayText += ".";
}
updateExpressionWithCurrentValue();
return displayText;
}
public String clear() {
storedValue = null;
pendingOperator = null;
startNewInput = true;
showingError = false;
displayText = "0";
expressionText = " ";
return displayText;
}
public String backspace() {
clearErrorIfNeeded();
if (startNewInput || displayText.length() == 1) {
displayText = "0";
startNewInput = true;
updateExpressionWithCurrentValue();
return displayText;
}
displayText = displayText.substring(0, displayText.length() - 1);
if ("-".equals(displayText)) {
displayText = "0";
startNewInput = true;
}
updateExpressionWithCurrentValue();
return displayText;
}
public String toggleSign() {
clearErrorIfNeeded();
if ("0".equals(displayText)) {
return displayText;
}
displayText = displayText.startsWith("-")
? displayText.substring(1)
: "-" + displayText;
updateExpressionWithCurrentValue();
return displayText;
}
public String percent() {
clearErrorIfNeeded();
return setCurrentValue(parseDisplay().divide(BigDecimal.valueOf(100), DIVISION_CONTEXT), true, "%");
}
public String inputPi() {
clearErrorIfNeeded();
return setCurrentValue(BigDecimal.valueOf(Math.PI), false, "pi");
}
public String applyOperator(String operator) {
clearErrorIfNeeded();
BigDecimal currentValue = parseDisplay();
if (storedValue == null) {
storedValue = currentValue;
} else if (!startNewInput && pendingOperator != null) {
storedValue = calculate(storedValue, currentValue, pendingOperator);
displayText = format(storedValue);
}
pendingOperator = operator;
startNewInput = true;
expressionText = format(storedValue) + " " + operator;
return displayText;
}
public String evaluate() {
clearErrorIfNeeded();
if (pendingOperator == null || storedValue == null) {
return displayText;
}
BigDecimal rightValue = parseDisplay();
String leftText = format(storedValue);
String rightText = format(rightValue);
BigDecimal result = calculate(storedValue, rightValue, pendingOperator);
if (!showingError) {
expressionText = leftText + " " + pendingOperator + " " + rightText + " =";
displayText = format(result);
storedValue = result;
pendingOperator = null;
startNewInput = true;
}
return displayText;
}
public String applyUnaryOperation(String operation) {
clearErrorIfNeeded();
BigDecimal value = parseDisplay();
return switch (operation) {
case "sqrt" -> {
requireNonNegative(value);
yield setCurrentValue(BigDecimal.valueOf(Math.sqrt(value.doubleValue())), true, "sqrt");
}
case "square" -> setCurrentValue(value.multiply(value, SCIENTIFIC_CONTEXT), true, "x^2");
case "inverse" -> {
requireNonZero(value);
yield setCurrentValue(BigDecimal.ONE.divide(value, DIVISION_CONTEXT), true, "1/x");
}
case "sin" -> setCurrentValue(BigDecimal.valueOf(Math.sin(value.doubleValue())), true, "sin");
case "cos" -> setCurrentValue(BigDecimal.valueOf(Math.cos(value.doubleValue())), true, "cos");
case "tan" -> setCurrentValue(BigDecimal.valueOf(Math.tan(value.doubleValue())), true, "tan");
case "ln" -> {
requirePositive(value);
yield setCurrentValue(BigDecimal.valueOf(Math.log(value.doubleValue())), true, "ln");
}
case "log" -> {
requirePositive(value);
yield setCurrentValue(BigDecimal.valueOf(Math.log10(value.doubleValue())), true, "log");
}
case "fact" -> setCurrentValue(BigDecimal.valueOf(factorial(value)), true, "n!");
default -> displayText;
};
}
public String getDisplayText() {
return displayText;
}
public String getExpressionText() {
return expressionText;
}
public BigDecimal getCurrentValue() {
clearErrorIfNeeded();
return parseDisplay();
}
public long getProgrammerValue() {
return getCurrentValue().longValue();
}
private String setCurrentValue(BigDecimal value, boolean startFresh, String prefix) {
displayText = format(value);
startNewInput = startFresh;
if (prefix == null || prefix.isBlank()) {
updateExpressionWithCurrentValue();
} else {
expressionText = prefix + "(" + displayText + ")";
}
return displayText;
}
private void clearErrorIfNeeded() {
if (showingError) {
clear();
}
}
private BigDecimal parseDisplay() {
return new BigDecimal(displayText);
}
private BigDecimal calculate(BigDecimal left, BigDecimal right, String operator) {
try {
return switch (operator) {
case "+" -> left.add(right, SCIENTIFIC_CONTEXT);
case "-" -> left.subtract(right, SCIENTIFIC_CONTEXT);
case "x", "×" -> left.multiply(right, SCIENTIFIC_CONTEXT);
case "/", "÷" -> {
requireNonZero(right);
yield left.divide(right, DIVISION_CONTEXT);
}
case "x^y" -> BigDecimal.valueOf(Math.pow(left.doubleValue(), right.doubleValue()));
default -> right;
};
} catch (ArithmeticException | IllegalArgumentException ex) {
showError(ex.getMessage() == null ? "Invalid operation" : ex.getMessage());
return BigDecimal.ZERO;
}
}
private void requireNonNegative(BigDecimal value) {
if (value.compareTo(BigDecimal.ZERO) < 0) {
throw new IllegalArgumentException("Invalid input");
}
}
private void requirePositive(BigDecimal value) {
if (value.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("Invalid input");
}
}
private void requireNonZero(BigDecimal value) {
if (BigDecimal.ZERO.compareTo(value) == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
}
private long factorial(BigDecimal value) {
if (value.scale() > 0 && value.stripTrailingZeros().scale() > 0) {
throw new IllegalArgumentException("Whole numbers only");
}
long number = value.longValue();
if (number < 0 || number > 20) {
throw new IllegalArgumentException("Range is 0-20");
}
long result = 1;
for (long i = 2; i <= number; i++) {
result *= i;
}
return result;
}
private void showError(String message) {
showingError = true;
pendingOperator = null;
storedValue = null;
startNewInput = true;
displayText = "Error";
expressionText = message;
}
private void updateExpressionWithCurrentValue() {
if (pendingOperator != null && storedValue != null) {
expressionText = format(storedValue) + " " + pendingOperator + " " + displayText;
} else if (!"0".equals(displayText)) {
expressionText = displayText;
} else {
expressionText = " ";
}
}
private String format(BigDecimal value) {
BigDecimal normalized = value.stripTrailingZeros();
if (normalized.scale() < 0) {
normalized = normalized.setScale(0);
}
return normalized.toPlainString();
}
}