读入数字文件并用Java计算平均值 [英] Read in number file and calculate average in java

查看:329
本文介绍了读入数字文件并用Java计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为平均值的txt文件,如下所示:

I have a txtfile called "averages" that looks like:

1 4 5 3 -1
2 8 9 3 2 -1
4 8 15 16 23 42 -1
3 -1

我希望能够读取每行并计算每行达到 -1时的平均值。我已经编写了读取文件中的代码并将其打印到命令行的代码,但是我很难找到每行的平均值。任何帮助将不胜感激。谢谢!

I want to be able to read in each line and calculate the average of each line whenever a "-1" is reached. I have written the code to read in the file and print it to the command line, I'm just having trouble finding the averages of each line. Any help would be greatly appreciated. Thanks!

import java.io.*;
import java.util.*;

public class Test {

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

        try {
            String currentLine;

            reader = new BufferedReader(new FileReader("averages.txt"));
            while  ((currentLine = reader.readLine()) != null) {
                System.out.println(currentLine);
            }
        } catch (IOException err) {
            err.printStackTrace();
        } finally {
            try {
                if (reader != null)reader.close();
            } catch (IOException err) {
                err.printStackTrace();
            }
        }

}
}


推荐答案

您可以执行以下操作:


  • currentLine 使用拆分方法:

String[] nums = currnetLine.split("\\s+");


  • nums 和将每个元素解析为 int ,然后将其添加到
    sum 变量

  • loop over the nums and parse each elements to int then add it to a sum variable

    int sum = 0;
    for (int i = 0; i < nums.length; i++) {
        int num = Integer.parseInt(nums[i]);
        if(num != -1) {
            sum += num;
        }
    }
    


  • 最后计算平均值。

  • Finally calculate the average.

    sum/(nums.length - 1);// -1 because you need to execlude the -1 at the end of your line
    


  • 这篇关于读入数字文件并用Java计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆