【问题标题】:Calculating Average/Max/Min from an array in Java从Java中的数组计算平均值/最大值/最小值
【发布时间】:2014-04-10 19:11:51
【问题描述】:

我的代码将读取名为“QuizScores.txt”的文件中的数字列表。但是,在此文件中,某些数字包含字母。我已经告诉我的程序简单地忽略这些实例并移动到下一个数字。我现在的问题是,如果我的代码一次只读取一行,我需要它来查看整个文件,读入它,计算平均值、最大值和最小值,最后将其输出到一个名为“ QuizStats.txt”。对此的任何帮助将不胜感激!谢谢!

测验分数:

45
63
74g
34.7
75
4
8
15
16
23
42
67f
34
67

代码:

import java.io.*;

public class ScoreReader {


    public static void main(String[] args) {
        BufferedReader reader = null;

        try {
               String currentLine;

               reader = new BufferedReader(new FileReader("QuizScores.txt"));
               while ((currentLine = reader.readLine()) != null) {

                   int sum = 0;
                   String[] nums = currentLine.split("\\s+");
                   for (int i = 0; i < nums.length; i++) {
                       try{
                           double num = Integer.parseInt(nums[i]);
                           if (num != -1) {
                               sum += num;
                           }
                       } catch( NumberFormatException err )
                       {

                       }
                   }

                   System.out.println(sum);
               }
            } catch (IOException err) {
                err.printStackTrace();
            } 
            catch (NumberFormatException err) {}
            finally {
                try {
                   if (reader != null){
                       reader.close();
                   }
                }
                   catch (IOException err) {
                    err.printStackTrace();
                   }
            }
    }
}

【问题讨论】:

  • 一次读一行有什么问题?
  • 你不想double sumdouble num = Double.parseDouble(nums[i]);吗?
  • 即使文件一次读取一行,我还能计算平均值、最大值和最小值吗?因为我无法让它发挥作用,并认为这是我的问题。
  • 你可以。添加一个计数器变量来计算您拥有的值的数量,然后将总和除以该计数器以获得平均值。为最大值和最小值添加另外两个变量 - 当您读取每个值时,将其与当前最大值和最小值进行比较,并根据需要更新最大值和最小值...
  • @ElliottFrisch 是的,你是对的,代码仍在进行中。不过,感谢您抓住这一点。 :)

标签: java arrays bufferedreader


【解决方案1】:
double min = 0.0;
double max  = 0.0;
int count = 0;



sum += num;
count++;
if (num > max) {
    max = num;
}
if (num < min) {
    min = num;
}
double avg = (double) sum/count;

那么 avg、sum、min 和 max 都是已知的。 我可能会从一开始就采取不同的方法,但上面的代码应该适用于您的代码。不过我还没有运行它。

【讨论】:

  • 如果我尝试将 avg/max/min 打印到命令行,这是否仍不会输出整个数字列表?
  • 我对你的问题有点困惑。您可以通过 System.out.println(String.valueOf(avg)); 打印平均值对于其他变量,请遵循此模式。这是你要问的吗??
【解决方案2】:

试试这个代码

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ScoreReader {

    public static void main(String[] args) {
        BufferedReader reader = null;
        double average = 200.0;
        double min = Double.MAX_VALUE;
        double max = Double.MIN_VALUE;
        int n = 1;
        String currentLine;
        double c;
        try {
            reader = new BufferedReader(new FileReader("QuizScores.txt"));
            System.out.println("--Quiz Scores--");
            while ((currentLine = reader.readLine()) != null) {
                try {
                    c = Double.parseDouble(currentLine);
                } catch (Exception ex) {
                    continue;
                }
                max = max > c ? max : c;
                min = min < c ? min : c;
                average += (c - average) / n;
                n++;
                System.out.println(c);
            }
            System.out.println("--Summary--");
            System.out.println("Average: " + average);
            System.out.println("Minimum: " + min);
            System.out.println("Maximum: " + max);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出

--Quiz Scores--
45.0
63.0
34.7
75.0
4.0
8.0
15.0
16.0
23.0
42.0
67.0
34.0
67.0
--Summary--
Average: 37.97692307692308
Minimum: 4.0
Maximum: 75.0

这是你要找的吗?

【讨论】:

  • 这正是我想要的!谢谢!
【解决方案3】:

逐行读取,仅解析数字并将其放入列表中,然后将该列表传递给函数,例如:

 public static Float getAverage(ArrayList <Float> x)
 {
    Float sum = 0.0f;

    for (Float a : x )
        sum += a;

    return sum / x.size();
 }

【讨论】:

  • 他为什么要那样做?保持总和,并计算您解析的数字....
  • 这也很好,但他也想将相同的数据用于其他计算,以便将其保存在一个数组中,但这只是个人喜好。
  • 如果数据集较小且操作简单,将读取和数据清理与计算分开将使代码更具可读性。对于像这样的小数据集,这种方法可能是合理的。
【解决方案4】:
 private class Statistics{

    public double min = -1;
    public double max;
    public double avg;
    public long sum;

    Statistics(List<Long> list){

        int count = 0;
        for (Long num : list) {
            sum += num;
            count++;

            if(min == -1) min= num;

            if (num > max) {
                max = num;
            }
            if (num < min) {
                min = num;
            }
        }

        this.avg = sum/(double)count;
    }

}

// 用法

    Statistics statistics = new Statistics(Arrays.asList(1l, 2l, 3l, 4l));

    System.out.println(statistics.avg);
    System.out.println(statistics.min);
    System.out.println(statistics.max);
    System.out.println(statistics.sum);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多