From bfe8b84de5ac441f5fbacd587e22dd842702e280 Mon Sep 17 00:00:00 2001 From: gxy <2107831483@qq.com> Date: Wed, 16 Oct 2024 10:38:02 +0800 Subject: [PATCH] =?UTF-8?q?16=E5=8F=B7=E7=AC=AC=E4=B8=80=E6=AC=A1=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Calculator.java | 40 +++++++++------------------------------- 1 file changed, 9 insertions(+), 31 deletions(-) diff --git a/Calculator.java b/Calculator.java index 1b3dee1..fc71457 100644 --- a/Calculator.java +++ b/Calculator.java @@ -2,12 +2,14 @@ import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; import javax.script.ScriptException; + public class Calculator extends JFrame implements ActionListener { private JTextField display; private StringBuilder input; + public Calculator() { input = new StringBuilder(); display = new JTextField(); @@ -16,13 +18,14 @@ public class Calculator extends JFrame implements ActionListener { display.setHorizontalAlignment(JTextField.RIGHT); display.setBackground(Color.LIGHT_GRAY); JPanel panel = new JPanel(); - panel.setLayout(new GridLayout(4, 4, 10, 10)); + panel.setLayout(new GridLayout(5, 4, 10, 10)); // Increase number of rows panel.setBackground(Color.GRAY); String[] buttons = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", - "C", "0", "=", "+" + "C", "0", ".", "+", // Add decimal point + "<-", "=", "" // Add delete button }; for (String text : buttons) { JButton button = new JButton(text); @@ -38,34 +41,9 @@ public class Calculator extends JFrame implements ActionListener { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } + + @Override public void actionPerformed(ActionEvent e) { - String command = e.getActionCommand(); - if (command.charAt(0) == 'C') { - input.setLength(0); - display.setText(""); - } else if (command.charAt(0) == '=') { - try { - double result = evaluate(input.toString()); - display.setText(String.valueOf(result)); - input.setLength(0); - } catch (ScriptException ex) { - display.setText("Error"); - input.setLength(0); - } - } else { - input.append(command); - display.setText(input.toString()); - } - } - private double evaluate(String expression) throws ScriptException { - ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript"); - return ((Number) engine.eval(expression)).doubleValue(); - } - public static void main(String[] args) { - SwingUtilities.invokeLater(() -> { - Calculator calculator = new Calculator(); - calculator.setVisible(true); - }); } -} \ No newline at end of file +}