計算文件的總和和平均值

[英]Calculate total and average from a file


I am trying to calculate total and average numbers from scores.csv but some reason it doesn't calculate.

我試圖從scores.csv計算總數和平均數,但有些原因不計算。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TotalAndAverage {

    public static void main(String[] args) {
        try {
            Scanner fin = new Scanner(new File("Scores.csv"));
            double total = 0, count = 0;
            while (fin.hasNextInt()) {
                total += fin.nextInt();
                count++;
            }
            System.out.println("Total score is " + total);
            System.out.println("Average score is " + (total/count));
            fin.close();
        } catch (FileNotFoundException e) {
            System.out.println("Scores.csv does not exists!");
        }
    }

}

When I run it shows, Total score is 0.0 Average score is NaN do you know why? I checked my file and it has data in it.

當我運行它時,總得分是0.0平均得分是NaN你知道為什么嗎?我檢查了我的文件,里面有數據。

1 个解决方案

#1


2  

As others in the comments have explained, the Scanner class's hasNextInt method works by breaking up the input stream into tokens, and returns false as soon as it hits a token that is not an integer. It's possible that there's non-number data in there for some reason that it's picking up on and returning false for.

正如評論中的其他人所解釋的那樣,Scanner類的hasNextInt方法通過將輸入流分解為標記來工作,並且一旦它到達非整數的標記就返回false。由於某種原因,它可能存在非數字數據,因為它正在接收並返回false。

A more proper way of handling this data would be to use hasNext() to control the termination of the while loop, allowing you to loop through each token of the file, skipping non-integer tokens and then terminate after all tokens have been consumed, not just when the first non-integer token is found:

處理這些數據的更合適的方法是使用hasNext()來控制while循環的終止,允許你循環遍歷文件的每個標記,跳過非整數標記,然后在消耗掉所有標記后終止,不僅在找到第一個非整數標記時:

while(fin.hasNext()) {
  if(fin.hasNextInt()) {
    int integer = fin.nextInt();
    total += integer;
    count++;
  }else{
    fin.next();
  }
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2018/04/17/5c1e078e5520f8b7ba42b42cda5d68b9.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com