gpt4 book ai didi

java - 从文本文件中查找平均值

转载 作者:行者123 更新时间:2023-12-01 10:09:59 25 4
gpt4 key购买 nike

我试图找到文本文件中同一行每一行的数字平均值。例如,如果这是文本文件:

8.7 6.5 0.1 3.2 5.7 9.9 8.3 6.5 6.5 1.5
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0

我想打印如下内容:

For Competitor #1, the average is 5.8625
For Competitor #2, the average is 0.0000
For Competitor #3, the average is 1.0000

这是我的代码。

import java.io.*;
import java.util.*;
import java.text.*;
public class BaseClass
{
public static void main(String args[]) throws IOException
{
NumberFormat fmt = NumberFormat.getNumberInstance();
fmt.setMinimumFractionDigits(4);
fmt.setMaximumFractionDigits(4);
Scanner sf = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt"));
int maxIndx = -1;
String text[] = new String[1000];

while (sf.hasNext()) {
maxIndx++;
text[maxIndx] = sf.nextLine();
}
sf.close();
int contestant = 0;

for (int j = 0; j <= maxIndx; j++) {
Scanner sc = new Scanner(text[j]);
double scoreAverage = 0;
double a = 0;
double array[] = new double[1000];
contestant++;
if (j <= 10) {
a += sc.nextDouble();
array[j] += a;
} else {
Arrays.sort(array);
int i = 0;
while (i < 10) {
scoreAverage += array[i];
i++;
}
}

String s = fmt.format(scoreAverage);
double d = Double.parseDouble(s);
System.out.println("For Competitor #" + contestant + ", the average is " + d);
}
}
}

打印

For the Competitor #1, the average is 0.0
For the Competitor #2, the average is 0.0
For the Competitor #3, the average is 0.0

最佳答案

你把问题搞得太复杂了。以下代码片段足以让您实现您在这里想要实现的目标。

这是代码片段:

public static void main (String[] args) throws Exception
{
Scanner in = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt"));
int counter = 0;
String line = null;
while(in.hasNext()) {
line = in.nextLine();
double sum = 0;
String[] splits = line.split(" ");
for(String s : splits) {
sum += Double.parseDouble(s);
}
System.out.println("For Competitor #" + (++counter)
+ ", the average is " + (sum/splits.length));
}
}

输出:

For Competitor #1, the average is 5.69
For Competitor #2, the average is 0.0
For Competitor #3, the average is 1.0

关于java - 从文本文件中查找平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36183892/

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