有没有Java大佬给看下代码

有没有大佬给看下这个代码哪里有问题。不管运行什么,都显示“ERROR”

package MYM;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MYM {

    // Declare frame, text field and buttons
    private JFrame frame;
    private JTextField textField;
    private String currentInput = "";

    // Constructor to setup GUI components
    public MYM() {
        // Create frame
        frame = new JFrame("Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 500);
        frame.setLayout(new BorderLayout());

        // Create text field for input and result display
        textField = new JTextField();
        textField.setFont(new Font("Arial", Font.PLAIN, 24));
        textField.setEditable(false);
        frame.add(textField, BorderLayout.NORTH);

        // Create panel for buttons
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(5, 4));  // Increased rows to 5 to add a row for the delete button

        // Define button labels
        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+",
            "C", "←"  // "←" is the delete button
        };

        // Add buttons to the panel
        for (String label : buttons) {
            JButton button = new JButton(label);
            button.setFont(new Font("Arial", Font.PLAIN, 24));
            button.addActionListener(new ButtonClickListener());
            panel.add(button);
        }

        // Add panel to the frame
        frame.add(panel, BorderLayout.CENTER);

        // Make frame visible
        frame.setVisible(true);
    }

    // ActionListener for button clicks
    private class ButtonClickListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();

            if (command.equals("=")) {
                // Evaluate the expression and show result
                try {
                    currentInput = evaluateExpression(currentInput);
                    textField.setText(currentInput);
                } catch (Exception ex) {
                    textField.setText("Error");
                }
            } else if (command.equals("C")) {
                // Clear the input
                currentInput = "";
                textField.setText(currentInput);
            } else if (command.equals("←")) {
                // Delete the last character
                if (currentInput.length() > 0) {
                    currentInput = currentInput.substring(0, currentInput.length() - 1);
                    textField.setText(currentInput);
                }
            } else {
                // Append the pressed button to the current input
                currentInput += command;
                textField.setText(currentInput);
            }
        }
    }

    // Function to evaluate simple arithmetic expressions
    private String evaluateExpression(String expression) {
        try {
            // Evaluate the expression using Java's built-in script engine
            javax.script.ScriptEngineManager mgr = new javax.script.ScriptEngineManager();
            javax.script.ScriptEngine engine = mgr.getEngineByName("JavaScript");
            Object result = engine.eval(expression);
            return result.toString();
        } catch (Exception e) {
            return "Error";
        }
    }

    public static void main(String[] args) {
        // Create an instance of the Calculator
        new MYM();
    }
}

3 Likes

眼泪哇,现在看到有人写swing了

www大学生的期末作业

我试试去

少年,学会debug先,断点一步步跟进去比在这让人猜更有效

        javax.script.ScriptEngine engine = mgr.getEngineByName("JavaScript");

NPE,JDK8 到JDK11 这个js引擎还存在,再高版本js已经被移除了,换8到11的版本运行 或者 加额外的js引擎

还有就是别 异常全部 return xxx 至少e.print出来,要不就是你都不知道怎么报错的

加输出打印

确实不太清楚,我去看看。因为能够正确输出图形界面,但是输出结果不对,就不太清楚哪里的问题,小白一个,见谅 :sob:

猜测你使用了JDK17或21,Nashorn 是 JDK 8 到 JDK 14 默认包含的 JavaScript 引擎,但从 JDK 15 开始已被移除,所以无法获取到js引擎: mgr.getEngineByName(“JavaScript”);

为了解决这个问题需要引入:

       <dependency>
            <groupId>org.mozilla</groupId>
            <artifactId>rhino</artifactId>
            <version>1.7.14</version>
        </dependency>

这是 Mozilla 提供的一个开源的 JavaScript 引擎.

修改后的代码



import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MYM {

    // Declare frame, text field and buttons
    private JFrame frame;
    private JTextField textField;
    private String currentInput = "";

    // Constructor to setup GUI components
    public MYM() {
        // Create frame
        frame = new JFrame("Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 500);
        frame.setLayout(new BorderLayout());

        // Create text field for input and result display
        textField = new JTextField();
        textField.setFont(new Font("Arial", Font.PLAIN, 24));
        textField.setEditable(false);
        frame.add(textField, BorderLayout.NORTH);

        // Create panel for buttons
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(5, 4));  // Increased rows to 5 to add a row for the delete button

        // Define button labels
        String[] buttons = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+", "C", "←"  // "←" is the delete button
        };

        // Add buttons to the panel
        for (String label : buttons) {
            JButton button = new JButton(label);
            button.setFont(new Font("Arial", Font.PLAIN, 24));
            button.addActionListener(new ButtonClickListener());
            panel.add(button);
        }

        // Add panel to the frame
        frame.add(panel, BorderLayout.CENTER);

        // Make frame visible
        frame.setVisible(true);
    }

    // ActionListener for button clicks
    private class ButtonClickListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();

            if (command.equals("=")) {
                // Evaluate the expression and show result
                try {
                    currentInput = evaluateExpressionForRhino(currentInput);
                    textField.setText(currentInput);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    textField.setText("Error");
                }
            } else if (command.equals("C")) {
                // Clear the input
                currentInput = "";
                textField.setText(currentInput);
            } else if (command.equals("←")) {
                // Delete the last character
                if (currentInput.length() > 0) {
                    currentInput = currentInput.substring(0, currentInput.length() - 1);
                    textField.setText(currentInput);
                }
            } else {
                // Append the pressed button to the current input
                currentInput += command;
                textField.setText(currentInput);
            }
        }
    }

    private String evaluateExpressionForRhino(String expression) {
        Context context = Context.enter();
        try {
            // 初始化标准全局对象
            Scriptable scope = context.initStandardObjects();

            // 定义并执行 JavaScript 代码
            Object result = context.evaluateString(scope, expression, "script", 1, null);

            // 获取并打印结果
            System.out.println(Context.toString(result)); // 输出结果
            return Context.toString(result);
        } finally {
            // 退出上下文
            Context.exit();
        }
    }

    // Function to evaluate simple arithmetic expressions
    private String evaluateExpression(String expression) {
        try {
            // Evaluate the expression using Java's built-in script engine
            javax.script.ScriptEngineManager mgr = new javax.script.ScriptEngineManager();
            javax.script.ScriptEngine engine = mgr.getEngineByName("JavaScript");
            Object result = engine.eval(expression);
            return result.toString();
        } catch (Exception e) {
            return "Error";
        }
    }

    public static void main(String[] args) {
        // Create an instance of the Calculator
        new MYM();
    }
}

非常感谢大佬!!

我一会儿去试试

似乎报错更严重了

swing !!! 不好意思,告辞

1 Like

啊,这。。。Swing
告辞。

好像是类型错误

catch呢?

这个代码的报错有么


报着错呢
你是不是没有引入 Rhino ? 如果你没有maven做包管理,你需要单独下载这个包的放入你的项目的