-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScientificCalculator1.java
More file actions
612 lines (548 loc) · 21.4 KB
/
Copy pathScientificCalculator1.java
File metadata and controls
612 lines (548 loc) · 21.4 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.geometry.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import java.util.*;
// Custom exception for calculator errors
class CalculatorException extends Exception {
public CalculatorException(String message) {
super(message);
}
}
// Interface for calculator operations (abstraction)
interface CalculatorOperation {
double execute(double... operands) throws CalculatorException;
String getSymbol();
}
// Abstract base class for operations (inheritance)
abstract class BaseOperation implements CalculatorOperation {
protected String symbol;
@Override
public String getSymbol() {
return symbol;
}
}
// Concrete operation classes (polymorphism)
class Addition extends BaseOperation {
public Addition() {
symbol = "+";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 2) throw new CalculatorException("Addition requires two operands");
return operands[0] + operands[1];
}
}
class Subtraction extends BaseOperation {
public Subtraction() {
symbol = "-";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 2) throw new CalculatorException("Subtraction requires two operands");
return operands[0] - operands[1];
}
}
class Multiplication extends BaseOperation {
public Multiplication() {
symbol = "x";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 2) throw new CalculatorException("Multiplication requires two operands");
return operands[0] * operands[1];
}
}
class Division extends BaseOperation {
public Division() {
symbol = "/";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 2) throw new CalculatorException("Division requires two operands");
if (operands[1] == 0) throw new CalculatorException("Division by zero");
return operands[0] / operands[1];
}
}
class Power extends BaseOperation {
public Power() {
symbol = "^";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 2) throw new CalculatorException("Power requires two operands");
return Math.pow(operands[0], operands[1]);
}
}
class Factorial extends BaseOperation {
public Factorial() {
symbol = "!";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 1) throw new CalculatorException("Factorial requires one operand");
if (operands[0] < 0 || operands[0] != Math.floor(operands[0]))
throw new CalculatorException("Factorial requires non-negative integer");
double fact = 1;
for (int i = 2; i <= operands[0]; i++) {
fact *= i;
}
return fact;
}
}
class Sine extends BaseOperation {
public Sine() {
symbol = "sin";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 1) throw new CalculatorException("Sine requires one operand");
return Math.sin(Math.toRadians(operands[0]));
}
}
class Cosine extends BaseOperation {
public Cosine() {
symbol = "cos";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 1) throw new CalculatorException("Cosine requires one operand");
return Math.cos(Math.toRadians(operands[0]));
}
}
class Tangent extends BaseOperation {
public Tangent() {
symbol = "tan";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 1) throw new CalculatorException("Tangent requires one operand");
double angle = Math.toRadians(operands[0]);
if (Math.abs(Math.cos(angle)) < 1e-10) throw new CalculatorException("Tangent undefined");
return Math.tan(angle);
}
}
class SquareRoot extends BaseOperation {
public SquareRoot() {
symbol = "sqrt";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 1) throw new CalculatorException("Square root requires one operand");
if (operands[0] < 0) throw new CalculatorException("Square root of negative number");
return Math.sqrt(operands[0]);
}
}
class NaturalLog extends BaseOperation {
public NaturalLog() {
symbol = "ln";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 1) throw new CalculatorException("Natural log requires one operand");
if (operands[0] <= 0) throw new CalculatorException("Log of non-positive number");
return Math.log(operands[0]);
}
}
class Logarithm extends BaseOperation {
public Logarithm() {
symbol = "log";
}
@Override
public double execute(double... operands) throws CalculatorException {
if (operands.length != 1) throw new CalculatorException("Logarithm requires one operand");
if (operands[0] <= 0) throw new CalculatorException("Log of non-positive number");
return Math.log10(operands[0]);
}
}
// Encapsulated calculator state
class CalculatorState {
private String result;
private String expression;
private ArrayList<String> tokens;
private boolean hasNumber;
private boolean hasDecimal;
public CalculatorState() {
reset();
}
public void reset() {
result = "";
expression = "";
tokens = new ArrayList<>();
hasNumber = false;
hasDecimal = false;
}
// Getters and setters
public String getResult() { return result; }
public void setResult(String result) { this.result = result; }
public String getExpression() { return expression; }
public void setExpression(String expression) { this.expression = expression; }
public ArrayList<String> getTokens() { return tokens; }
public boolean hasNumber() { return hasNumber; }
public void setHasNumber(boolean hasNumber) { this.hasNumber = hasNumber; }
public boolean hasDecimal() { return hasDecimal; }
public void setHasDecimal(boolean hasDecimal) { this.hasDecimal = hasDecimal; }
}
public class ScientificCalculator1 extends Application {
private TextField textField;
private Label exprLabel;
private CalculatorState state;
private Map<String, CalculatorOperation> operations;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Calculator");
primaryStage.setResizable(false);
// Initialize state and operations
state = new CalculatorState();
initializeOperations();
// Main layout
BorderPane root = new BorderPane();
root.setStyle("-fx-background-color:purple;");
// Text display panel
VBox textPanel = new VBox(2);
textPanel.setPadding(new Insets(10));
textPanel.setStyle("-fx-border-color: gray; -fx-border-width: 2; -fx-background-color: #F0F0F0;");
textPanel.setPrefSize(316, 80);
textPanel.setAlignment(Pos.CENTER_RIGHT);
exprLabel = new Label("");
exprLabel.setFont(new Font("Arial", 20));
exprLabel.setTextFill(Color.GRAY);
exprLabel.setMaxWidth(312);
textField = new TextField("0");
textField.setFont(new Font("Arial", 32));
textField.setEditable(false);
textField.setAlignment(Pos.CENTER_RIGHT);
textField.setStyle("-fx-background-color: #F0F0F0; -fx-border-color: transparent;");
textField.setPrefWidth(312);
textPanel.getChildren().addAll(exprLabel, textField);
root.setTop(textPanel);
BorderPane.setMargin(textPanel, new Insets(25, 34, 15, 34));
// Button panel
GridPane buttonPanel = new GridPane();
buttonPanel.setStyle("-fx-background-color: #E6E6FA; -fx-border-color: gray; -fx-border-width: 2;");
buttonPanel.setPrefSize(316, 322);
buttonPanel.setHgap(0);
buttonPanel.setVgap(0);
buttonPanel.setAlignment(Pos.CENTER);
// Button creation and setup
String[] buttonLabels = {
"C", "DEL", "π", "x^y", "x!",
"sin", "(", ")", "e", "√",
"cos", "7", "8", "9", "÷",
"tan", "4", "5", "6", "x",
"ln", "1", "2", "3", "-",
"log", ".", "0", "=", "+"
};
for (int i = 0; i < buttonLabels.length; i++) {
Button btn = new Button(buttonLabels[i]);
btn.setFont(new Font("Arial", buttonLabels[i].equals("-") ? 23 : 17));
btn.setPrefSize(63.2, 64.4);
if (Character.isDigit(buttonLabels[i].charAt(0)) || buttonLabels[i].equals("0")) {
btn.setStyle("-fx-background-color: #DCDCDC;");
} else if (buttonLabels[i].equals("=")) {
btn.setStyle("-fx-background-color: orange;");
}
int row = i / 5;
int col = i % 5;
buttonPanel.add(btn, col, row);
addButtonAction(btn, buttonLabels[i]);
}
root.setCenter(buttonPanel);
BorderPane.setMargin(buttonPanel, new Insets(0, 34, 30, 34));
Scene scene = new Scene(root, 384, 484);
primaryStage.setScene(scene);
primaryStage.show();
}
private void initializeOperations() {
operations = new HashMap<>();
operations.put("+", new Addition());
operations.put("-", new Subtraction());
operations.put("x", new Multiplication());
operations.put("/", new Division());
operations.put("^", new Power());
operations.put("!", new Factorial());
operations.put("sin", new Sine());
operations.put("cos", new Cosine());
operations.put("tan", new Tangent());
operations.put("sqrt", new SquareRoot());
operations.put("ln", new NaturalLog());
operations.put("log", new Logarithm());
}
private void addButtonAction(Button btn, String label) {
btn.setOnAction(e -> {
try {
String currentText = textField.getText();
switch (label) {
case "C":
state.reset();
textField.setText("0");
exprLabel.setText("");
break;
case "DEL":
handleDelete(currentText);
break;
case "π":
appendConstant(currentText, "π", "pi");
break;
case "e":
appendConstant(currentText, "e", "e");
break;
case "x^y":
appendOperator(currentText, "^", "^");
break;
case "x!":
appendOperator(currentText, "!", "!");
break;
case "sin":
case "cos":
case "tan":
case "ln":
case "log":
appendFunction(currentText, label);
break;
case "√":
appendFunction(currentText, "sqrt");
break;
case "(":
case ")":
appendParenthesis(currentText, label);
break;
case "÷":
appendOperator(currentText, "÷", "/");
break;
case "x":
appendOperator(currentText, "x", "x");
break;
case "-":
appendOperator(currentText, "-", "-");
break;
case "+":
appendOperator(currentText, "+", "+");
break;
case ".":
appendDecimal(currentText);
break;
case "=":
calculateResult();
break;
default: // Numbers
appendNumber(currentText, label);
break;
}
} catch (CalculatorException ex) {
textField.setText("Error");
state.setResult("Error");
exprLabel.setText("");
}
});
}
private void handleDelete(String currentText) {
if (!currentText.equals("0") && currentText.length() > 1) {
String newString = currentText.substring(0, currentText.length() - 1);
textField.setText(newString);
String expr = state.getExpression();
if (expr.endsWith(".")) {
state.setHasDecimal(false);
}
if (expr.endsWith(",")) {
state.setExpression(expr.substring(0, expr.length() - 2));
} else if (!expr.isEmpty()) {
state.setExpression(expr.substring(0, expr.length() - 1));
}
} else {
textField.setText("0");
state.setExpression("");
state.setHasNumber(false);
state.setHasDecimal(false);
}
}
private void appendConstant(String currentText, String display, String token) {
textField.setText(currentText.equals("0") ? display : currentText + display);
state.setExpression(state.getExpression() + "," + token);
state.setHasNumber(false);
state.setHasDecimal(false);
}
private void appendOperator(String currentText, String display, String token) {
if (currentText.equals("0") && !token.equals("!")) {
state.setExpression(state.getExpression() + "0");
}
char lastChar = currentText.charAt(currentText.length() - 1);
if (lastChar == '-' || lastChar == 'x' || lastChar == '+' || lastChar == '÷') {
String newText = currentText.substring(0, currentText.length() - 1) + display;
textField.setText(newText);
state.setExpression(state.getExpression().substring(0, state.getExpression().length() - 1) + token);
} else {
textField.setText(currentText + display);
state.setExpression(state.getExpression() + "," + token);
}
state.setHasNumber(false);
state.setHasDecimal(false);
}
private void appendFunction(String currentText, String label) {
textField.setText(currentText.equals("0") ? label + "(" : currentText + label + "(");
state.setExpression(state.getExpression() + "," + label + ",(");
state.setHasNumber(false);
state.setHasDecimal(false);
}
private void appendParenthesis(String currentText, String label) {
textField.setText(currentText.equals("0") ? label : currentText + label);
state.setExpression(state.getExpression() + "," + label);
state.setHasNumber(false);
state.setHasDecimal(false);
}
private void appendDecimal(String currentText) {
if (!currentText.endsWith(".")) {
if (state.hasNumber() && !state.hasDecimal()) {
state.setExpression(state.getExpression() + ".");
textField.setText(currentText + ".");
} else if (!state.hasNumber() && !state.hasDecimal()) {
state.setExpression(state.getExpression() + ",0.");
textField.setText(currentText + "0.");
}
state.setHasNumber(true);
state.setHasDecimal(true);
}
}
private void appendNumber(String currentText, String label) {
if (currentText.equals("0")) {
textField.setText(label);
} else {
textField.setText(currentText + label);
}
if (state.hasNumber()) {
state.setExpression(state.getExpression() + label);
} else {
state.setExpression(state.getExpression() + "," + label);
}
state.setHasNumber(true);
}
private int precedence(String symbol) {
switch (symbol) {
case "+":
case "-":
return 1;
case "x":
case "/":
return 2;
case "^":
return 3;
case "!":
case "sin":
case "cos":
case "tan":
case "sqrt":
case "ln":
case "log":
return 4;
default:
return 0;
}
}
private boolean isOperator(String symbol) {
return operations.containsKey(symbol);
}
private String infixToPostfix() throws CalculatorException {
Stack<String> stack = new Stack<>();
StringBuilder postfix = new StringBuilder();
List<String> tokens = new ArrayList<>(state.getTokens());
tokens.add(")");
stack.push("(");
for (String token : tokens) {
if (token.isEmpty()) continue;
if (token.equals("(")) {
stack.push(token);
} else if (token.equals(")")) {
while (!stack.isEmpty() && !stack.peek().equals("(")) {
postfix.append(stack.pop()).append(",");
}
if (stack.isEmpty()) throw new CalculatorException("Mismatched parentheses");
stack.pop(); // Remove '('
} else if (isOperator(token)) {
while (!stack.isEmpty() && !stack.peek().equals("(") &&
precedence(stack.peek()) >= precedence(token)) {
postfix.append(stack.pop()).append(",");
}
stack.push(token);
} else {
postfix.append(token).append(",");
}
}
while (!stack.isEmpty()) {
String token = stack.pop();
if (token.equals("(")) throw new CalculatorException("Mismatched parentheses");
if (!token.equals(")")) {
postfix.append(token).append(",");
}
}
return postfix.toString();
}
private double evaluate(String postfix) throws CalculatorException {
Stack<Double> stack = new Stack<>();
String[] tokens = postfix.split(",");
for (String token : tokens) {
if (token.isEmpty()) continue;
if (isOperator(token)) {
CalculatorOperation op = operations.get(token);
if (op instanceof Factorial || op instanceof Sine || op instanceof Cosine ||
op instanceof Tangent || op instanceof SquareRoot || op instanceof NaturalLog ||
op instanceof Logarithm) {
if (stack.isEmpty()) throw new CalculatorException("Invalid expression: missing operand");
double operand = stack.pop();
stack.push(op.execute(operand));
} else {
if (stack.size() < 2) throw new CalculatorException("Invalid expression: missing operands");
double operand2 = stack.pop();
double operand1 = stack.pop();
stack.push(op.execute(operand1, operand2));
}
} else {
try {
if (token.equals("pi")) {
stack.push(Math.PI);
} else if (token.equals("e")) {
stack.push(Math.E);
} else {
stack.push(Double.parseDouble(token));
}
} catch (NumberFormatException e) {
throw new CalculatorException("Invalid number format: " + token);
}
}
}
if (stack.size() != 1) throw new CalculatorException("Invalid expression: incomplete evaluation");
return stack.pop();
}
private void calculateResult() throws CalculatorException {
state.getTokens().clear();
String[] exprTokens = state.getExpression().split(",");
for (String token : exprTokens) {
if (!token.isEmpty()) {
state.getTokens().add(token);
}
}
if (state.getTokens().isEmpty()) throw new CalculatorException("Empty expression");
String postfix = infixToPostfix();
double result = evaluate(postfix);
state.setResult(String.format("%.10f", result).replaceAll("0+$", "").replaceAll("\\.$", ""));
StringBuilder displayExpr = new StringBuilder();
for (String token : state.getTokens()) {
if (token.equals("/")) displayExpr.append("÷");
else if (token.equals("sqrt")) displayExpr.append("√");
else if (token.equals("pi")) displayExpr.append("π");
else displayExpr.append(token);
}
exprLabel.setText(displayExpr + "=");
textField.setText(state.getResult());
state.setExpression(state.getResult());
state.setHasDecimal(state.getResult().contains("."));
state.setHasNumber(true);
state.getTokens().clear();
}
}