【发布时间】:2015-03-12 18:06:44
【问题描述】:
每次单击新按钮时,它都会替换文本字段中的 num 变量。当我单击不同的按钮时,我希望它一个接一个地显示每个新数字,然后最终我将对它们进行加/减/乘和除,如果可能的话,您可以告诉我如何对两个不同的数字块进行数学运算.
您的帮助将不胜感激
private class TheHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
//add values to buttons
String num = "";
if(e.getSource()==btn[0]){
//tDisplay.setText("7");
num = "7";
}else if(e.getSource()==btn[1]){
//tDisplay.setText("8");
num = "8";
}else if(e.getSource()==btn[2]){
//tDisplay.setText("9");
num = "9";
}else if(e.getSource()==btn[5]){
//tDisplay.setText("4");
num = "4";
}else if(e.getSource()==btn[6]){
//tDisplay.setText("5");
num = "5";
}else if(e.getSource()==btn[7]){
//tDisplay.setText("6");
num = "6";
}else if(e.getSource()==btn[10]){
//tDisplay.setText("1");
num = "1";
}else if(e.getSource()==btn[11]){
//tDisplay.setText("2");
num = "2";
}else if(e.getSource()==btn[12]){
//tDisplay.setText("3");
num = "3";
}else if(e.getSource()==btn[15]){
//tDisplay.setText("0");
num = "0";
}
//set the values to the text field
tDisplay.setText(num);
}
}
【问题讨论】:
-
保持数字区域为字符串,并在字符串右侧追加数字,对于算术运算,将字符串解析为整数/双精度
-
一旦您的应用程序按预期工作,您应该将应用程序代码放在codereview.stackexchange.com 上以进行建设性的批评。
标签: java user-interface jbutton jtextfield calculator