各位大师.我是一个刚学JAVA的菜鸟.昨天编写了一个只有加减的计算器..可是问题就一大堆..当我PRESS加号或者减号的时候.之前输入的数字就会全部清零.而且加减算法上也有问题.能帮我解决一下吗??谢谢
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class calc extends Applet implements ActionListener
{ //declare global variables and constants
private JTextField displayBox;
private Button[] numButtons;
private String[] num = {"7","8","9","4","5","6","1","2","3","0","","C","+","-","="};
private int[] indexSorter = {7,8,9,4,5,6,1,2,3,0,10,11,12,13,14};
private long total=0;
private long subTotal=0;
private long numIdx=0;
private String numString="0";
private boolean firstNo = true;
//start method of applet
public void init()
{ GridBagLayout gLayout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gLayout);
this.setBackground(new Color(0,100,150));
this.setForeground(Color.black);
//text box for calculator display
Panel p = new Panel();
p.setLayout(new FlowLayout());
displayBox = new JTextField(15);
displayBox.setHorizontalAlignment(JTextField.RIGHT);
displayBox.setEditable(false);
displayBox.addActionListener(this);
p.add(displayBox);
//set gridBag constraints for this component (panel)
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10,10,10,10);
c.anchor = GridBagConstraints.NORTH;
gLayout.setConstraints(p,c);
add(p);
//buttons for numbers
Panel q = new Panel();
q.setLayout(new GridLayout(5,3,20,20));
numButtons = new Button[num.length];
for (int i=0;i<num.length;i++)
{ numButtons[indexSorter[i]] = new Button(num[i]);
numButtons[indexSorter[i]].addActionListener(this);
q.add(numButtons[indexSorter[i]]);
}
c.gridheight = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.CENTER;
c.weighty = 1.0;
gLayout.setConstraints(q,c);
add(q);
}
//actions performed when button input recognised by ActionListener
public void actionPerformed(ActionEvent e)
{ Object source = e.getSource();
for (int i=0;i<10;i++)
{ if (source == numButtons[i])
{ numIdx=i;
if (firstNo)
{ numString="";
firstNo=false;
}
numString=numString+Long.toString(numIdx);
displayBox.setText(numString);
subTotal=(subTotal*10)+numIdx;
}
}
//clear
if (source == numButtons[11])
{ numString="0";
subTotal=0;
total=0;
displayBox.setText(numString);
firstNo=true;
}
//+
if (source == numButtons[12])
{
total=total+subTotal;
subTotal=0;
numString=Long.toString(0);
displayBox.setText(numString);
firstNo=true;
}
//-
if (source == numButtons[13])
{ total=total-subTotal;
subTotal=0;
numString=Long.toString(0);
displayBox.setText(numString);
firstNo=true;
}
//=
if (source == numButtons[14])
{ numString=Long.toString(total);
displayBox.setText(numString);
firstNo=true;
}
}
}