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

标签 java arrays text

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

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/

相关文章:

java - Android Twitter异常错误:(

java - 调用 commit 后将文档添加到 Lucene Index Writer

objective-c - 我可以使用 NSMutableArray 分配数组大小吗?

c# - 为什么空文本文件包含 3 个字节?

android - 文本输入类型的人名不起作用

java - 管道上的拆分未按预期运行

java - Swing 应用程序窗口未显示更改

javascript - 如何调用 "document.getElementBytag()"创建的数组中的元素?

c# - 在不初始化长度的情况下向数组添加值

mysql查询文本替换问题