gpt4 book ai didi

java - 如何对 java 文本文件进行排序以获得中位数?

转载 作者:行者123 更新时间:2023-11-30 03:53:10 24 4
gpt4 key购买 nike

到目前为止我有下面的代码。我知道中位数是错误的,因为我在其中放置了数字,而我真正想要的是程序自行从文件中提取这些数字,因为数字可能会发生变化。我不知道如何让程序获取这 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");
}
}

最佳答案

执行此操作需要几个步骤。

  1. 在程序的开头,创建一个 ArrayList<Double>用于存储您的值。

  2. 在主循环中,使用列表的 add方法在您阅读时添加每个值。

  3. 在循环结束时,使用 Collections.sort对您的列表进行排序。

  4. 使用以下逻辑计算中位数。

    • 如果列表的大小为零,则没有中位数。
    • 如果列表的大小是奇数,则中位数是位置 size() / 2 处的值列表中的。
    • 如果列表的大小是偶数,则中位数是位置 size() / 2 - 1 处的值的平均值和size() / 2列表中的。

我故意没有给你代码,因为我认为你很喜欢学习如何自己做这件事。但如果您需要有关任何特定步骤的更多详细信息,请随时发表评论。

关于java - 如何对 java 文本文件进行排序以获得中位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23880008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com