首页 > 解决方案 > 基于来自 JTextField 的输入运行非标准评估(sin、cos、tan)

问题描述

我正在编写一个程序,它利用提供的库 ScriptEngineManager 来尝试编写一个超出 +、-、/ 和 * 基本功能的数学计算器。我将如何在现有代码中实现这一点。

我已经尝试过使用 .replace,尽管我可能错误地实现了它。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class GUIRunner {

    public static void main(String args[]) {
        JFrame f = new JFrame("megamath1.0");
        f.setSize(300,300); 
        f.setLocation(100,150);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JFrame.setDefaultLookAndFeelDecorated(true);
        JLabel labelM = new JLabel("Enter Equation: ");
        labelM.setBounds(50, 50, 200, 30);
        JLabel label = new JLabel(); 
        label.setBounds(50,100,200,30);
        label.setVisible(true);
        JTextField motto1 = new JTextField();
        //set size of the text box
        motto1.setBounds(50, 100, 200, 30);
       //add elements to the frame
        f.add(labelM);
        f.add(motto1);
        f.setLayout(null);
        f.setVisible(true);
        JButton b = new JButton("Submit");
        b.setBounds(50, 150, 100, 30);
        b.addActionListener(new ActionListener() {
         @Override
            public void actionPerformed(ActionEvent arg0) {
                String inputText = motto1.getText(); 

            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
                try {
                motto1.setText("Output: " + engine.eval(inputText));
                } catch (ScriptException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

       });
       //add button to the frame
       f.add(b);
       f.add(label);
}
}

它目前确实适用于标准计算,例如上面提供的计算(+、-、*、/),只需将文本字段中的文本更改为正确的答案。我怎样才能实现更复杂的数学

标签: javaswingjlabeljtextfieldscriptengine

解决方案


因此,目前您只需将输入文本放入 JavaScript 引擎并希望它能够正常工作。如果你真的想坚持这种方法,用户必须知道 JavaScript 才能使用计算器。例如,如果您输入Math.sin(42),您将得到 的正弦值42

如果您想实现更方便的数学语法,类似于真正的数学,您需要为数学表达式编写自己的脚本引擎。有一些库可以帮助解决这个问题,但你需要很好地理解你在做什么。


推荐阅读