-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
171 lines (153 loc) · 6.7 KB
/
Copy pathMain.java
File metadata and controls
171 lines (153 loc) · 6.7 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
// Importing necessary libraries for the program
import javax.swing.*; // For creating GUI components like frames, buttons, and text fields.
import java.awt.*; // For graphical elements such as layouts, fonts, and colors.
import java.awt.event.ActionEvent; // For handling events like button clicks.
import java.awt.event.ActionListener; // Interface for handling ActionEvent (e.g., button clicks).
import java.awt.event.KeyAdapter; // Simplifies handling keyboard events by overriding necessary methods.
import java.awt.event.KeyEvent; // Represents keypress events (e.g., key pressed, released, or typed).
// Main class to create a calculator application
public class Main {
public static void main(String[] args) {
// Create the main frame for the calculator
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
// Create a text field for user input/output and configure its properties
JTextField textField = new JTextField();
textField.setFont(new Font("Arial", Font.PLAIN, 24));
textField.setHorizontalAlignment(JTextField.RIGHT);
frame.add(textField, BorderLayout.NORTH);
// Add key listener to handle Enter and Delete key functionality
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
// Evaluate the expression when Enter is pressed
textField.setText(evaluate(textField.getText()));
} else if (e.getKeyCode() == KeyEvent.VK_DELETE) {
// Clear the text field when Delete is pressed
textField.setText("");
}
}
});
// Create a panel for calculator buttons
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4, 10, 10));
// Define the calculator buttons
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
"C", "(", ")", "^"
};
// Add buttons to the panel and set their action listeners
for (String text : buttons) {
JButton button = new JButton(text);
button.setFont(new Font("Arial", Font.PLAIN, 24));
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("=")) {
// Evaluate the expression when "=" button is pressed
textField.setText(evaluate(textField.getText()));
} else if (command.equals("C")) {
// Clear the text field when "C" button is pressed
textField.setText("");
} else {
// Append the button text to the current text field content
if (textField.getText().equals("0")) {
textField.setText(command);
} else {
textField.setText(textField.getText() + command);
}
}
}
});
}
// Add the button panel to the frame
frame.add(panel);
frame.setVisible(true);
}
// Method to evaluate the mathematical expression
private static String evaluate(String expression) {
try {
// Calculate the result using a custom evaluation function
double result = eval(expression);
if (result == (long) result) {
// Return result as integer if it's a whole number
return String.format("%d", (long) result);
} else {
// Return result as double
return String.format("%s", result);
}
} catch (Exception e) {
// Return "Error" for invalid expressions
return "Error";
}
}
// Method to parse and evaluate the expression
private static double eval(final String str) {
class Parser {
int pos = -1, c;
// Advance to the next character
void nextChar() {
c = (++pos < str.length()) ? str.charAt(pos) : -1;
}
// Check and consume a specific character
boolean eat(int charToEat) {
while (c == ' ') nextChar();
if (c == charToEat) {
nextChar();
return true;
}
return false;
}
// Parse the entire expression
double parse() {
nextChar();
double x = parseExpression();
if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char) c);
return x;
}
// Parse an expression (handles addition and subtraction)
double parseExpression() {
double x = parseTerm();
for (;;) {
if (eat('+')) x += parseTerm(); // Addition
else if (eat('-')) x -= parseTerm(); // Subtraction
else return x;
}
}
// Parse a term (handles multiplication and division)
double parseTerm() {
double x = parseFactor();
for (;;) {
if (eat('*')) x *= parseFactor(); // Multiplication
else if (eat('/')) x /= parseFactor(); // Division
else return x;
}
}
// Parse a factor (handles parentheses, numbers, and exponentiation)
double parseFactor() {
if (eat('+')) return parseFactor(); // Unary plus
if (eat('-')) return -parseFactor(); // Unary minus
double x;
int startPos = this.pos;
if (eat('(')) { // Parentheses
x = parseExpression();
eat(')');
} else if ((c >= '0' && c <= '9') || c == '.') { // Numbers
while ((c >= '0' && c <= '9') || c == '.') nextChar();
x = Double.parseDouble(str.substring(startPos, this.pos));
} else {
throw new RuntimeException("Unexpected: " + (char) c);
}
if (eat('^')) x = Math.pow(x, parseFactor()); // Exponentiation
return x;
}
}
return new Parser().parse();
}
}