0

I am building a GUI application with Netbeans that takes multiple float numbers after each button click. I am using an event listener and every time you enter the number and click it the button it should show the sum, the number of values entered, maximum value, minimum value, and average. The issue is that I don't know how to go about the max and min values, also every time I click it just updates the number I entered and it doesn't add to the previous number.

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

   float _min;
   float _max;
   float _avg = 0;
   float _total = 0;
   float _sum = 0;
   float _number = 0 ;


   try {
       _number = Float.parseFloat(this.numberIn.getText());
   }
   catch (NumberFormatException e) {
       JOptionPane.showMessageDialog(this, "Invalid input", "Error",JOptionPane.ERROR_MESSAGE);
       }

   _total++;
   _sum += _number;
   _avg = _sum/_total;

   this.sumLbl.setText(" Sum: " + _sum);


    }                                        
1
  • Your variables need to be field variables, which are bound to the instance of the class. In your code are only local variables. Make sure that you understand the difference: homeandlearn.co.uk/java/field_variables.html Commented Mar 20, 2020 at 20:51

2 Answers 2

1

That is because you define your vars inside the event listener.

actionPerformed function will set your int vals to 0 on each action.

 float _min;
 float _max;
 float _avg = 0; --->here
 float _total = 0; --->here
 float _sum = 0; --->here
 float _number = 0 ; --->here
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot guys, I am new to Java, I didn’t know it was that simple, any idea on how to go on determining the max and minimum values?
1

That happens because every time you click on that button, you actually creating new variables _avg, _total etc.. You need to exclude these variable outside jButton1ActionPerformed(java.awt.event.ActionEvent evt) method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.