我有一個基本的計算器,所以當按下相同的按鈕時,JTextField被保存爲字符串形式,這就是問題,它是字符串形式,所以我不知道如何解決方程式。我試過使用JavaScript引擎,但無法弄清楚。任何幫助?如何在Java中的字符串中解決基本的數學公式?
//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();
}
}
謝謝,我安裝了lib,代碼是什麼? –