[英]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.我对 java 很陌生,想寻求帮助。 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?有什么建议么?
Your mean is not right because sum
variable store only last value from array.你的意思是不对的,因为
sum
变量只存储数组中的最后一个值。 A condition should be sum += unit[i]
.条件应该是
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.