到目前为止,我有以下代码。我知道中位数是错误的,因为我已经在其中放置了数字,我真正想要的是程序从文件中提取这些数据,因为数字可能会改变。我不知道如何让程序得到2个数字,以便检索和计算中位数。请帮忙。我对此非常陌生,整天都花了我这么远!
package trials;
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class trials2 {
public static void main(String[] args) throws IOException {
// This is a Scanner object that reads from the keyboard
Scanner in = new Scanner(System.in);
// The following is set to find the file
System.out.println("Please enter the name of your data file: ");
String fileName = in.next();
// The file is then to be scanned
Scanner fileToRead = new Scanner(new File(fileName));
// This loop finds the contents within the file
double sum = 0;
int numStudents = 0;
double maxVal = 0, minVal = 0;
boolean bFirstTime = true;
double currVal;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
numStudents++;
currVal = fileToRead.nextDouble();
// The following will find the maximum and minimum values within the file
if (bFirstTime) {
maxVal = currVal;
minVal = currVal;
bFirstTime = false;
} else {
maxVal = Math.max(maxVal,currVal);
minVal = Math.min(minVal, currVal);
}
sum += currVal;
} else {
fileToRead.next();
}
}
// Prints out comments and results
System.out.println("***Welcome to the Exam Statistics Program!!***");
System.out.println();
System.out.println("Minimum = " + minVal);
System.out.println("Maximum = " + maxVal);
System.out.println("Average score: " + sum/numStudents);
System.out.println();
System.out.println("Number of scores by letter grade: ");
System.out.println();
System.out.println("There are " + numStudents + " scores");
}
}
答案 0 :(得分:2)
这样做有几个步骤。
在程序开头,创建一个ArrayList<Double>
来存储您的值。
在主循环中,使用列表的add
方法在读取时添加每个值。
在循环结束时,使用Collections.sort
对列表进行排序。
使用以下逻辑计算出中位数。
size() / 2
位置的值。size() / 2 - 1
和size() / 2
位置的平均值。我故意没有给你代码,因为我觉得你很乐意学习如何为自己做这件事。但如果您需要有关任何特定步骤的更多详细信息,请随时发表评论。