我有一个设置的基本计算器,所以当按下相等按钮时,JTextField 以字符串形式保存,这就是问题所在,它是字符串形式,所以我不知道如何求解方程。我尝试过使用 JavaScript 引擎,但无法弄清楚。有什么帮助吗?
//actionListener
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(oneButton)){
input1 = 1;
text.setText(text.getText()+input1);}
else if (e.getSource().equals(twoButton)){
input2 = 2;
text.setText(text.getText()+input2);}
else if(e.getSource().equals(threeButton)){
input3 = 3;
text.setText(text.getText()+input3);}
else if(e.getSource().equals(fourButton)){
input4 = 4;
text.setText(text.getText()+input4);}
else if(e.getSource().equals(fiveButton)){
input5 = 5;
text.setText(text.getText()+input5);}
else if(e.getSource().equals(sixButton)){
input6 = 6;
text.setText(text.getText()+input6);}
else if(e.getSource().equals(sevenButton)){
input7 = 7;
text.setText(text.getText()+input7);}
else if(e.getSource().equals(eightButton)){
input8 = 8;
text.setText(text.getText()+input8);}
else if(e.getSource().equals(nineButton)){
input9 = 9;
text.setText(text.getText()+input9);}
else if(e.getSource().equals(zeroButton)){
input0 = 0;
text.setText(text.getText()+input0);}
else if(e.getSource().equals(plusButton)){
text.setText(text.getText()+" + ");}
else if(e.getSource().equals(minusButton)){
text.setText(text.getText()+" - ");}
else if(e.getSource().equals(timesButton)){
text.setText(text.getText()+" * ");}
else if(e.getSource().equals(dividButton)){
text.setText(text.getText()+" / ");}
else if(e.getSource().equals(clrButton)){
text.setText("");}
else if(e.getSource().equals(enterButton)){
eq = text.getText();
//trying the javascript ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
text.setText((String) engine.eval(eq));
} catch (ScriptException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}