In: Computer Science
*****Using Java
Write a program that finds the standard deviation while also using a graphical user interface.
package test.gui.stddev;
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StdDevGUI {
public StdDevGUI(){
Frame f= new Frame();
f.setBackground(Color.orange);
f.setTitle("Standard Deviation Calculator");
TextField tf1,tf2;
Label l1,l2;
Button btn;
l1= new Label("Enter numbers(Comma separarated):");
l1.setBounds(50,60,300,20);
tf1 = new TextField();
tf1.setBounds(50,90,150,40);
l2= new Label("Calculated Standard Deviation:");
l2.setBounds(50,150,300,20);
tf2 = new TextField();
tf2.setBounds(50,180,150,40);
tf2.setEditable(false);
btn = new Button("Calculate SD");
btn.setBounds(50,240,100,30);
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String data = tf1.getText();
String[] dataArr = data.split(",");
double[] dblArr = new
double[dataArr.length];
for(int i = 0 ; i < dataArr.length;
i++){
dblArr[i] =
Double.parseDouble(dataArr[i]);
}
double stdDev = calculateStdDev(dblArr);
tf2.setText(String.valueOf(stdDev));
}
});
f.add(l1);
f.add(tf1);
f.add(l2);
f.add(tf2);
f.add(btn);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String []args) {
new StdDevGUI();
}
/**
* calculate standard deviation
* @param dataArr
* @return
*/
private static double calculateStdDev(double[] dataArr){
double sum = 0.0;
double stdDev = 0.0;
int length = dataArr.length;
for(double dbl : dataArr) {
sum = sum + dbl;
}
//System.out.println(sum);
double mean = sum/length;
for(double dbl: dataArr) {
double powered = Math.pow(dbl - mean, 2);
stdDev = stdDev + powered;
}
//System.out.println(stdDev);
return Math.sqrt(stdDev/length);
}
}
=======================
OUTPUT
=======================