From 2e3e6ccf7f27eb8e4737b0a306c97b136e5e61c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E4=BD=B3=E5=AA=9B?= <2487706653@qq.com> Date: Wed, 16 Oct 2024 10:43:01 +0800 Subject: [PATCH] =?UTF-8?q?=E9=99=88=E4=BD=B3=E5=AA=9B1016=E6=8F=90?= =?UTF-8?q?=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Calculator.java | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/Calculator.java b/Calculator.java index fc71457..dae743c 100644 --- a/Calculator.java +++ b/Calculator.java @@ -42,8 +42,41 @@ public class Calculator extends JFrame implements ActionListener { 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.equals("<-")) { // Delete the last character + if (input.length() > 0) { + input.setLength(input.length() - 1); + display.setText(input.toString()); + } + } 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); + }); } }