簡體   English   中英

從Java中的數組計算平均值/最大值/最小值

[英]Calculating Average/Max/Min from an array in Java

我的代碼可以讀取名為“ 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 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;

然后,平均,總和,最小和最大都是已知的。 從一開始我可能會采取其他方法,但是上面的代碼應該與您的代碼一起使用。 我還沒有運行它。

試試這個代碼

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

這是你想要的?

逐行讀取僅解析數字並將其放入列表,然后將該列表傳遞給以下函數:

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

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

    return sum / x.size();
 }
 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM