简体   繁体   English

读入数字文件并用Java计算平均值

[英]Read in number file and calculate average in java

I have a txtfile called "averages" that looks like: 我有一个名为“ averages”的txtfile,看起来像:

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

I want to be able to read in each line and calculate the average of each line whenever a "-1" is reached. 我希望能够读取每一行并计算每当达到“ -1”时的每一行的平均值。 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();
            }
        }

}
}

You could do it by doing the following: 您可以执行以下操作:

  • split the currentLine using split method: 使用split方法分割currentLine

     String[] nums = currnetLine.split("\\\\s+"); 
  • loop over the nums and parse each elements to int then add it to a sum variable 循环遍历nums并将每个元素解析为int然后将其添加到sum变量

     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 

I'd try something like this: 我会尝试这样的事情:

int sum = 0;

String[] values = currentLine.split(" ");

for (String value : values) {
    int n = Integer.parseInt(value);

    if (n < 0) {
        break;
    }

    sum += n;
}

int count = values.length - 1;
// calculate average from sum and count

In Java 7+, the Scanner object is available and has a variety of useful functions to use. 在Java 7+中,“扫描程序”对象可用,并且具有各种有用的功能。

1.) First read in the line Scanner scanner = new Scanner("1 51 2 52"); 1.)首先读入Scanner扫描器= new Scanner(“ 1 51 2 52”);

2.) From your code above, if you have a space delimiter, it is easy to work with scanner.useDelimiter(" "); 2)从上面的代码中,如果您有一个空格定界符,则可以很容易地使用scan.useDelimiter(“”);

3.) If scanner.hasNext() then scanner.next() for the next string. 3.)如果为scanner.hasNext(),则为下一个字符串使用scanner.next()。

Iterate the list using Integer.parseInt("1") to get the value, sum, then average. 使用Integer.parseInt(“ 1”)迭代列表以获取值,总和,然后取平均值。

Please try this: 请尝试以下方法:

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);
                StringTokenizer st=new StringTokenizer(currentLine," ");
                int count=st.countTokens();
                int array[]=new int[count-1];
                int i=0;
            while(st.hasMoreTokens()&&i!=count-1)
             {
                array[i]=Integer.valueOf(st.nextToken());
                i=i+1;
             }
        int sum=0;
            for(int x=0;x<array.length;x++)
                {
                    sum=sum+array[x];
                }
        float average=(float)sum/array.length;
        System.out.println("The average of this line is: "+average);
            }
        } catch (IOException err) {
            err.printStackTrace();
        } finally {
            try {
                if (reader != null)reader.close();
            } catch (IOException err) {
                err.printStackTrace();
            }
        }
}
}

My logic is that you read a line at a time and separate them by spaces. 我的逻辑是,您一次读取一行,并用空格隔开。 Then you convert those separated string into Integer. 然后,将这些分隔的字符串转换为Integer。 Last step is add them up and do some math to get the average. 最后一步是将它们加起来并做一些数学运算以获得平均值。

Hope this helps. 希望这可以帮助。 Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM