简体   繁体   中英

Java OOP to show the standard deviation

Whenever I click the compute button the standard deviation is always wrong. Here's my code:

int test[] = new int[99];
int counter = 0;
double mean, sd = 0, fmean, square, sd2;

//first button labeled as "accept number"
// after put a numbers i need to click the button to add the numbers into array
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)   {                                         
               counter = counter +1;//to increment counter after the user will clicked the button
        test[0] = Integer.parseInt(jTextField2.getText());


    for (int i=0;i<test.length;i++)
    {
        mean += test[i];

    }

    fmean = mean / counter;

    for (int i=0; i<test.length; i++)
    {
        sd += ((test[i] - fmean)*(test[i] - fmean)) / (test.length - 1);
    }


    sd2 = Math.sqrt(sd);
    jTextField1.setText(String.valueOf(counter));
    jTextField2.setText("");//to clear the text inside the textfield

}


// second button labeled as "compute"
//to show the result when the compute button clicked
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) 
{          



jTextField3.setText(String.valueOf(fmean));


jTextField4.setText(String.valueOf(sd2));
}

I see two problems:

  1. You always put the input in the same array position (ie 0), this should be test[counter - 1] = Integer.parseInt(jTextField2.getText()); instead.
  2. Your for loops should not run to test.length (ie 99), but to counter .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM