I wrote a calculator, but the way i concatenate my numbers is so bad because after calculation lets say "5 + 2" when i press equal button it gives "7", the problem comes when i want to do another calculation lets say "6+1" it doesn't do it this way when i press 6 button it gives "76+1" i.e concatenating my result with the new calculation, i tried to fix it but i couldn't without disrupting another functionality. Below is part of the code.
private void NineActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
TextField.setText(TextField.getText()+"9");
}
private void OneActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
TextField.setText(TextField.getText()+"1");
}
private void TwoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
TextField.setText(TextField.getText()+"2");
}
private void ThreeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
TextField.setText(TextField.getText()+"3");
}
private void FourActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
TextField.setText(TextField.getText()+"4");
}
private void FiveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
TextField.setText(TextField.getText()+"5");
}
Most simple solution : add clear button and on press clear the text.
The typical solution.:
do something like this:
onequalbuttonclick [your equal button action function]
set equalPress=true;
in other functions do something like this
private void NineActionPerformed(java.awt.event.ActionEvent evt) {
if(equalPress){
textField.setText(9);
equalPress=false;
}
else
textField.setText((Integer.parseInt(TextField.getText()) + 9));
}
Comment on your code:
Instead of these functions just add one actionPerformed event in your class. and then you can use the getSource()
method to find the button clicked.