Unexpected result when triggering the same calculator button

0

I created a calculator by netbeans, which is working if only one operation is done. But if the user clicks on = (equal button) the result adds the first value entered.

Example:
 I typed 1 + 2
 I pressed =
 I get 3

But if I click again on the = button, I have result 4 instead of 5. My code looks like this:

I've created these variables in the main class

public class TelaCalculadora extends javax.swing.JFrame {
double numA;
String opera;
double numB;

I created the class to add

public class soma {
double a;
double b;
double res;
public double somar()
{
   res = a+b;       
   return res;
}

The action when a button is triggered

private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    String numeroACalcular;
    numeroACalcular = txtVisor.getText() + btn1.getText();
    txtVisor.setText(numeroACalcular);

}

When you click the "+" button

private void btnSomaActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    opera = "somar";
    numA = Double.parseDouble(txtVisor.getText());
    txtVisor.setText("");

and when you click "="

private void btnResultadoActionPerformed(java.awt.event.ActionEvent evt) {                                             


    numB = Double.parseDouble(txtVisor.getText());
    if(opera == "somar")
    {
        soma resu = new soma();

            resu.a = numA;
            resu.b = numB;
            resu.somar();
        txtVisor.setText(Double.toString(resu.res));


     }
    
asked by anonymous 09.04.2016 / 14:19

1 answer

0

The problem is that by pressing = , you are overwriting the old value of numB in btnResultadoActionPerformed() , with the current value (in this case, the result) and adding up with the already typed value of numA .

The logic of your application is not very good. The soma class could very well receive the values already at startup and return the result when calling the somar() method, not allowing direct access to its attributes.

I suggest you take a look at in this example because it is complete and would only make minor changes to the result method for work as you expect.

Anyway, here's a solution to the problem of your current code:

private void btnResultadoActionPerformed(java.awt.event.ActionEvent evt) {                                             

    numB = Double.parseDouble(txtVisor.getText());
    if(opera == "somar")
    {
        soma resu = new soma();

            resu.a = numA;
            resu.b = numB;
            numA = numB;
            resu.somar();
        txtVisor.setText(Double.toString(resu.res));

 }
    
09.04.2016 / 16:32