Unexpected result when triggering equal calculator knob

Asked

Viewed 116 times

0

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

Example:
I typed 1+2
pressed =
receive 3

But if I click the button again =, I have to score 4, not 5. My code is as follows:

I 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 on "="

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));


     }

1 answer

0


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

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

I suggest you take a look in this example, because it is complete and would only take minor modifications to the result method to 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));

 }
  • Thank you very much, Diego. I’ll see.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.