Calculate total and average from a file

时间:2018-04-17 01:37:26

标签: java file csv io try-catch

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

  onQuestionSubmit() {
   fetch('url', {
    credentials: 'same-origin',
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
     databaserow: this.state.blahblah,
   }),
  })
 }

When I run it shows, 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!"); } } } do you know why? I checked my file and it has data in it.

1 个答案:

答案 0 :(得分:2)

正如评论中的其他人所解释的那样,Scanner类的hasNextInt方法通过将输入流分解为标记来工作,并且一旦它到达非整数的标记就返回false。由于某种原因,它可能存在非数字数据,因为它正在接收并返回false。

处理这些数据的更合适的方法是使用hasNext()来控制while循环的终止,允许你循环遍历文件的每个标记,跳过非整数标记然后终止已经消耗了令牌,而不仅仅是在找到第一个非整数令牌时:

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