我是Java的新手,我正在制作一个计算器,我似乎无法让Math.sqrt
处理任何不仅仅是数字的数字(即Math.sqrt(6 + 3
))。请有人能告诉我我做错了什么。
等于按钮:
//Equals button
JButton equals = new JButton();
equals.setText("=");
panel.add(equals);
frame.add(panel);
equals.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent eq) {
if(calculation.getText().contains("Math.sqrt")){
calculation.setText(calculation.getText().replace("Math.sqrt(", ""));
calculation.setText(Double.toString(Math.sqrt(Double.valueOf(calculation.getText()).longValue())));
}
else{
double answer = (Equals.eval(calculation.getText()));
Double answer1 = Double.valueOf(answer);
calculation.setText(Double.toString(answer));
}
}
});;
Square root 按钮:
//root
JButton root = new JButton();
root.setText("Sqrt");
panel.add(root);
frame.add(panel);
root.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
calculation.setText(calculation.getText() + "Math.sqrt(");
}
});;
感谢。