我非常擅长做java并且在阅读基本教程后尝试做计算器。我一直试图破解这个错误已经有一段时间了,这就是如何将我的总和作为一个字符串变成一个表现并评估它。 (为了让你知道,我已经尝试过.parseInt和engine.eval,这只会导致错误。)
以下是重要的代码:
private JTextField txt = new JTextField(10);
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
DoubleEvaluator evaluator = new DoubleEvaluator();
Double result = evaluator.evaluate(txt.getText());
String x = String.valueOf(result);
if(((JButton)e.getSource()).getText() != "="){
txt.setText(txt.getText()+((JButton)e.getSource()).getText());}
else{
txt.setText(x);
}
}}
请有人能为我提供(简单)回答我的需求。
如果已经提出这个问题,我很抱歉 谢谢youuuuu:)
下面的其余代码:
package calculator;
import java.awt.FlowLayout;
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.JTextField;
import com.fathzer.soft.javaluator.DoubleEvaluator;
public class calculator_gui extends JFrame{
private JButton
b1 = new JButton("1"),
b2 = new JButton("2"),
b3 = new JButton("3"),
b4 = new JButton("4"),
b5 = new JButton("5"),
b6 = new JButton("6"),
b7 = new JButton("7"),
b8 = new JButton("8"),
b9 = new JButton("9"),
b0 = new JButton("0"),
bx = new JButton("*"),
bp = new JButton("+"),
bs = new JButton("-"),
bd = new JButton("/"),
br = new JButton("=");
private JTextField txt = new JTextField(10);
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
DoubleEvaluator evaluator = new DoubleEvaluator();
Double result = evaluator.evaluate(txt.getText());
String x = String.valueOf(result);
if(!((JButton)e.getSource()).getText().equals("=")){
txt.setText(txt.getText()+ ((JButton)e.getSource()).getText());}
else{
txt.setText(x);
}
}}
private ButtonListener bl = new ButtonListener();
public calculator_gui(){
b1.addActionListener(bl);
b2.addActionListener(bl);
b3.addActionListener(bl);
b4.addActionListener(bl);
b5.addActionListener(bl);
b6.addActionListener(bl);
b7.addActionListener(bl);
b8.addActionListener(bl);
b9.addActionListener(bl);
b0.addActionListener(bl);
bp.addActionListener(bl);
bs.addActionListener(bl);
bx.addActionListener(bl);
br.addActionListener(bl);
bd.addActionListener(bl);
setLayout(new FlowLayout());
add(txt);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
add(bx);
add(b0);
add(bd);
add(bp);
add(bs);
add(br);
}
public static void main(String[] args){
//run(new Button(), 240, 180);
calculator_gui frame = new calculator_gui();
frame.setTitle("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(160, 210);
frame.setVisible(true);
frame.setResizable(false);
}
}