【发布时间】:2019-05-10 15:30:28
【问题描述】:
我正在编写一个程序,它利用提供的库 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);
}
}
它目前确实适用于标准计算,例如上面提供的那些(+、-、*、/),只需将文本字段中的文本更改为正确的答案。我怎样才能实现更复杂的数学
【问题讨论】:
标签: java swing jlabel jtextfield scriptengine