Reputation: 9
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);
}
Upvotes: 0
Views: 249
Reputation: 106
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.
Upvotes: 1
Reputation: 868
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
Upvotes: 1