Repository navigation
Expand file tree
/
Copy pathCalculator.java
More file actions
218 lines (190 loc) · 7.9 KB
/
Copy pathCalculator.java
File metadata and controls
218 lines (190 loc) · 7.9 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
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private double firstOperand = Double.NaN;
private String currentOp = "";
private boolean startNewNumber = true;
public Calculator() {
setTitle("Scientific Calculator");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Comfortable larger size; we'll pack after setting preferred sizes
getContentPane().setBackground(new Color(240, 240, 245));
setLayout(new BorderLayout(12,12));
display = new JTextField();
display.setFont(new Font("SansSerif", Font.BOLD, 48));
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
display.setText("0");
display.setBackground(new Color(28, 30, 34));
display.setForeground(Color.WHITE);
display.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(12, 12, 12, 12),
BorderFactory.createLineBorder(new Color(50, 50, 60), 2)));
// place display in a top panel to control padding/height
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setBackground(getContentPane().getBackground());
display.setPreferredSize(new Dimension(760, 140));
topPanel.setBorder(BorderFactory.createEmptyBorder(14, 14, 10, 14));
topPanel.add(display, BorderLayout.CENTER);
add(topPanel, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setBackground(getContentPane().getBackground());
panel.setLayout(new GridLayout(6, 4, 10, 10));
String[] buttons = {
"AC", "pi", "x^2", "sqrt",
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
"sin", "cos", "tan", "log"
};
for (String text : buttons) {
JButton b = new JButton(text);
b.setFont(new Font("SansSerif", Font.BOLD, 20));
b.setFocusPainted(false);
b.addActionListener(this);
b.setPreferredSize(new Dimension(140, 72));
// Color coding
if (text.equals("AC")) {
b.setBackground(new Color(220, 80, 80));
b.setForeground(Color.WHITE);
} else if (text.equals("=") ) {
b.setBackground(new Color(80, 180, 120));
b.setForeground(Color.WHITE);
} else if (text.matches("[0-9]|") || text.equals(".")) {
b.setBackground(Color.WHITE);
b.setForeground(Color.DARK_GRAY);
} else if (text.equals("+") || text.equals("-") || text.equals("*") || text.equals("/")) {
b.setBackground(new Color(255, 165, 60));
b.setForeground(Color.WHITE);
} else {
// scientific/function buttons
b.setBackground(new Color(80, 140, 220));
b.setForeground(Color.WHITE);
}
b.setBorder(BorderFactory.createLineBorder(new Color(200,200,200)));
panel.add(b);
}
add(panel, BorderLayout.CENTER);
// Final sizing
pack();
setSize(820, 720);
setResizable(false);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Calculator calc = new Calculator();
calc.setVisible(true);
});
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
try {
if (cmd.equals("AC")) {
clearAll();
return;
}
if (isNumberOrDot(cmd)) {
if (startNewNumber) {
display.setText(cmd.equals(".") ? "0." : cmd);
startNewNumber = false;
} else {
if (cmd.equals(".") && display.getText().contains(".")) return;
display.setText(display.getText().equals("0") && !cmd.equals(".") ? cmd : display.getText() + cmd);
}
return;
}
if (isOperator(cmd)) {
applyPendingOperator();
currentOp = cmd;
startNewNumber = true;
return;
}
if (cmd.equals("=")) {
applyPendingOperator();
currentOp = "";
startNewNumber = true;
return;
}
// Scientific functions apply immediately to current display value
if (isScientific(cmd)) {
double val = parseDisplay();
double result = 0;
switch (cmd) {
case "sin": result = Math.sin(Math.toRadians(val)); break;
case "cos": result = Math.cos(Math.toRadians(val)); break;
case "tan": result = Math.tan(Math.toRadians(val)); break;
case "log": result = Math.log10(val); break;
case "sqrt": result = Math.sqrt(val); break;
case "x^2": result = val * val; break;
case "pi": result = Math.PI; break;
default: throw new UnsupportedOperationException("Unknown function: " + cmd);
}
display.setText(formatResult(result));
startNewNumber = true;
return;
}
} catch (ArithmeticException ex) {
showError("Error: Division by zero is not allowed");
clearAll();
} catch (NumberFormatException ex) {
showError("Invalid Input");
clearAll();
} catch (Exception ex) {
showError("An unexpected error occurred: " + ex.getMessage());
clearAll();
}
}
private boolean isNumberOrDot(String s) {
return s.matches("\\d") || s.equals(".");
}
private boolean isOperator(String s) {
return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/");
}
private boolean isScientific(String s) {
return s.equals("sin") || s.equals("cos") || s.equals("tan") || s.equals("log") || s.equals("sqrt") || s.equals("x^2") || s.equals("pi");
}
private void applyPendingOperator() {
double displayed = parseDisplay();
if (Double.isNaN(firstOperand)) {
firstOperand = displayed;
display.setText(formatResult(firstOperand));
} else if (!currentOp.isEmpty()) {
double result = 0;
switch (currentOp) {
case "+": result = firstOperand + displayed; break;
case "-": result = firstOperand - displayed; break;
case "*": result = firstOperand * displayed; break;
case "/":
if (displayed == 0) throw new ArithmeticException("Division by zero");
result = firstOperand / displayed; break;
default: throw new UnsupportedOperationException("Unknown operator: " + currentOp);
}
firstOperand = result;
display.setText(formatResult(result));
}
}
private double parseDisplay() {
String txt = display.getText();
if (txt == null || txt.trim().isEmpty()) throw new NumberFormatException("Empty input");
return Double.parseDouble(txt);
}
private String formatResult(double v) {
if (Double.isInfinite(v) || Double.isNaN(v)) return "Error";
if (Math.rint(v) == v) return String.valueOf((long)v);
return String.valueOf(v);
}
private void clearAll() {
display.setText("0");
firstOperand = Double.NaN;
currentOp = "";
startNewNumber = true;
}
private void showError(String msg) {
JOptionPane.showMessageDialog(this, msg, "Error", JOptionPane.ERROR_MESSAGE);
}
}