'How do I sum all the values placed in an array from a single JTextField by looping or otherwise to get the mean or average?
I'm quite new to java and wanted to ask for help. I've been trying to make a statistic calculator where it finds the mean, median, mode, maximum, and minimum of a user inputted set. I've been stuck trying to find the right command where it can read all values instead of just reading a single value for mean. Here's the code as of now:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class proto extends JFrame implements ActionListener{
private JFrame frame = new JFrame();
private JTextField un, s1;
private JButton cal;
private JPanel p1, p2;
private int[] unit;
private int s1n, length;
private double sum, mean;
private JLabel set, r1, r2, r3, r4, r5;
private String str;
private String[] astr;
public proto() {
setTitle("Prototype");
setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cal = new JButton("Calculate");
s1 = new JTextField(20);
p1 = new JPanel(new GridLayout(0, 1));
p2 = new JPanel();
set = new JLabel("Set 1");
r1 = new JLabel("Mean: ");
r2 = new JLabel("Median: ");
r3 = new JLabel("Mode: ");
r4 = new JLabel("Minimum: ");
r5 = new JLabel("Maximum: ");
sum = 0;
setLayout(new BorderLayout());
add(p1, BorderLayout.WEST);
add(p2, BorderLayout.SOUTH);
p1.add(set);
p1.add(s1);
s1.addActionListener(this);
p1.add(r1);
p1.add(r2);
p1.add(r3);
p1.add(r4);
p1.add(r5);
p2.add(cal, BorderLayout.SOUTH);
cal.addActionListener(this);
}
public void actionPerformed(ActionEvent sigh) {
if(sigh.getSource() == cal) {
try {
astr = s1.getText().split(", ");
unit = new int[astr.length];
for (int i = 0; i < astr.length; i++) {
unit[i] = Integer.parseInt(astr[i]);
sum =+ unit[i]; //basically sum = sum + Integer.parseInt(astr[i])
}
} catch (NumberFormatException fk) {
}
mean = sum / astr.length;
r1.setText("Mean: " + mean);
System.out.println(unit);
}
}
public static void main(String[] args) {
new proto();
}
Any suggestions?
Solution 1:[1]
Your mean is not right because sum variable store only last value from array. A condition should be sum += unit[i].
Your codition is:
int[] arr = {2, 5, 8, 10};
for(int i = 0; i < arr.length; i++)
{
sum =+ arr[i] // sum = +arr[i]
}
// sum variable store last value from from array
sum: 10
Condition should be:
int[] arr = {2, 5, 8, 10};
for(int i = 0; i < arr.length; i++)
{
sum += arr[i] // sum = sum + arr[i]
}
// sum variable store sum of array
sum: 25
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
