簡體   English   中英

從txt文件中讀取行並將其相加並取平均值

[英]Read lines from a txt file and add and average them

所以基本上我必須寫一個數字類似的txt文件:

1
2
3
4
5
6
7
8
9
10

然后將它們中的每一個相加並將它們彼此相加,得出總計55,然后將它們平均55/10以得到我的答案。

好吧,我可以使用以下命令輕松地將數字寫到txt文件中:

PrintWriter outputFile = new PrintWriter("output.txt");

    outputFile.println("1");
    outputFile.println("2");
    outputFile.println("3");
    outputFile.println("4");
    outputFile.println("5");
    outputFile.println("6");
    outputFile.println("7");
    outputFile.println("8");
    outputFile.println("9");
    outputFile.println("10");
    outputFile.close();

但是如何重新讀回它們並將它們轉換成總和為55的數字? 我的大多數嘗試只是將它們全部讀回或讀入,最后進行怪異的計算,例如

3
5
9
14
20
27
ect.
public static void main(String[]args){
 int total = 0;
 int counter = 0;
 Scanner inFile = null;

 try{
 inFile = new Scanner(new File("fileName.txt"));

 while(inFile.hasNext()){
  total += inFile.nextInt();
  counter++;
 }

}catch(FileNotFoundException e){
 e.printStackTrace();
 }


System.out.println("Average: "+total/counter);
}

您可以使用java.io.BufferedReader讀取文件,即

BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));

看一下BufferedReader API中的readLine()方法。 有關更多信息,請閱讀教程

暫無
暫無

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

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