我编写了从 .dat 文件中打印出整数并将它们移动到常规数组中并打印出平均值和标准偏差的代码。现在我想从常规数组切换到 ArrayList。我已经编写了下面的代码,但似乎运行不正确。
.dat 文件包括以下数字:“51 52 55 57 58 61 62 63 66 66 66 70 72 73 74 75 75 77 77 78 79 81 82 84 86 87 88 91 94 97”
谢谢您的帮助!
import java.io.*;
import java.lang.Math;
import java.util.*;
import java.text.DecimalFormat;
public class gradeSorter{
public static void main(String[] args) throws IOException {
{
DecimalFormat fmt = new DecimalFormat("0.000");
Scanner scanner = new Scanner(new File("grades.dat"));
double average;
double deviation;
double sum = 0;
int number = 0;
ArrayList<Integer> element = new ArrayList<Integer>();
for (int count = 0; count < element.size(); count++)
{
while (scanner.hasNext())
{
element.add(scanner.nextInt());
number = element.get(count);
for (int item : element){
sum += number;
System.out.println(number);
}
}
average = sum / element.size();
for (int i = 0; i < element.size(); i++)
{
sum += Math.pow((element.get(i) - average),2);
}
deviation = Math.sqrt((sum / (30-1)));
System.out.println("The average of these grades is : " + fmt.format(average));
System.out.println("The standard deviation of these grades is: " + fmt.format(deviation));
}
}
}
}
更新***
import java.io.*;
import java.lang.Math;
import java.util.*;
import java.text.DecimalFormat;
public class gradeSorter{
public static void main(String[] args) throws IOException {
{
DecimalFormat fmt = new DecimalFormat("0.000");
Scanner scanner = new Scanner(new File("grades.dat"));
double average;
double deviation;
double sum = 0;
int number = 0;
int newnumber = 0;
ArrayList<Integer> element = new ArrayList<Integer>();
while (scanner.hasNextInt())
{
element.add(scanner.nextInt());
}
for (int item : element){
sum += item;
System.out.println(item);
}
average = sum / element.size();
for (int i = 0; i < element.size(); i++)
{
newnumber += Math.pow((element.get(i) - average),2);
}
deviation = Math.sqrt(newnumber / (element.size()));
System.out.println("The average of these grades is : " + fmt.format(average));
System.out.println("The standard deviation of these grades is: " + fmt.format(deviation));
}
}
}
----jGRASP exec: javagradeSorter
51 52 55 57 58 61 62 63 66 66 66 70 72 73 74 75 75 77 77 78 79 81 82 84 86 87 88 91 94 97 这些等级的平均值为:73.233 这些等级的标准差为:12.288
----jGRASP:操作完成。