From 660a2d946ea3660a96229a413619ab7d2023e92b Mon Sep 17 00:00:00 2001 From: chm <3227492039@qq.com> Date: Thu, 17 Oct 2024 17:11:54 +0800 Subject: [PATCH] 3 --- SimpleCalculator.java | 55 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/SimpleCalculator.java b/SimpleCalculator.java index 79d227d..1ee5a1c 100644 --- a/SimpleCalculator.java +++ b/SimpleCalculator.java @@ -45,4 +45,59 @@ public class SimpleCalculator extends JFrame { } 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); + }); + } } \ No newline at end of file