From d79d1eb369048ae46709ef8caa4678e8802be40d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=BF=97=E5=98=89?= <282227179@qq.com> Date: Thu, 10 Oct 2024 17:14:01 +0800 Subject: [PATCH] 1 --- Calculator.java | 97 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 Calculator.java diff --git a/Calculator.java b/Calculator.java new file mode 100644 index 0000000..47fcb96 --- /dev/null +++ b/Calculator.java @@ -0,0 +1,97 @@ +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +public class Calculator extends JFrame implements ActionListener { + private JTextField display; + private double num1 = 0, num2 = 0, result = 0; + private String operation = ""; + + public Calculator() { + setTitle("简易计算器"); + setSize(400, 600); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setLayout(new BorderLayout()); + + // 显示屏 + display = new JTextField(); + display.setEditable(false); + display.setHorizontalAlignment(JTextField.RIGHT); + add(display, BorderLayout.NORTH); + + // 按钮面板 + JPanel panel = new JPanel(); + panel.setLayout(new GridLayout(4, 4, 10, 10)); + String[] buttons = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "C", "0", "=", "+"}; + for (String text : buttons) { + JButton button = new JButton(text); + button.addActionListener(this); + panel.add(button); + } + add(panel, BorderLayout.CENTER); + + setVisible(true); + } + + @Override + public void actionPerformed(ActionEvent e) { + String command = e.getActionCommand(); + if (command.equals("C")) { + clearDisplay(); + } else if (command.equals("=")) { + calculateResult(); + } else { + handleInput(command); + } + } + + private void handleInput(String input) { + if (input.matches("[0-9]")) { + display.setText(display.getText() + input); + } else { + operation = input; + num1 = Double.parseDouble(display.getText()); + display.setText(""); + } + } + + private void calculateResult() { + num2 = Double.parseDouble(display.getText()); + switch (operation) { + case "+": + result = num1 + num2; + break; + case "-": + result = num1 - num2; + break; + case "*": + result = num1 * num2; + break; + case "/": + if (num2 != 0) { + result = num1 / num2; + } else { + display.setText("Error"); + return; + } + break; + case "%": + result = num1 % num2; + break; + } + display.setText(String.valueOf(result)); + } + + private void clearDisplay() { + display.setText(""); + num1 = 0; + num2 = 0; + result = 0; + operation = ""; + } + + public static void main(String[] args) { + new Calculator(); + } +}