chm 1 month ago
parent 222835ed25
commit 660a2d946e

@ -46,3 +46,58 @@ public class SimpleCalculator extends JFrame {
add(panel, BorderLayout.CENTER); add(panel, BorderLayout.CENTER);
} }
private class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("0123456789.".contains(command)) {
display.setText(display.getText().concat(command));
} else if ("+-*/".contains(command)) {
operand1 = Double.parseDouble(display.getText());
operator = command.charAt(0);
userIsTypingSecondNumber = true;
display.setText(""); // Clear the display for the next number
} else if (command.equals("=")) {
if (userIsTypingSecondNumber) {
operand2 = Double.parseDouble(display.getText());
double result = 0;
switch (operator) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if (operand2 != 0) {
result = operand1 / operand2;
} else {
display.setText("Error");
return;
}
break;
}
display.setText(String.valueOf(result));
operand1 = result; // Store the result for possible chain operations
userIsTypingSecondNumber = false; // Reset for next operation
}
} else if (command.equals("C")) {
display.setText("");
operand1 = 0;
operand2 = 0;
userIsTypingSecondNumber = false;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}
Loading…
Cancel
Save