java - Java中如何连续读取一个文件?

标签 java

有一个文件包含 5 组 8 个数字。每组都是参赛者的“分数”(共5名参赛者)。我的任务是读取文件得到每组,剪出最高分和最低分,然后计算每个参赛者的平均分。 该任务还要求我们使用一种方法来计算平均值,因此不允许我将整个程序塞到 main 方法中。

以下是供引用的数据集:

8.4 9.1 8.5 8.4 9.1 8.7 8.8 9.1
7.0 7.0 7.0 7.0 7.0 7.0 7.0 7.0
8.0 7.9 8.0 8.0 8.0 8.0 8.0 8.1
7.0 9.1 8.5 8.4 7.0 8.7 8.8 9.1
7.0 7.9 7.0 7.8 7.0 5.0 7.0 7.5

但是,我遇到了一个问题。每个参赛者的平均分计算是相同的。这是因为每次调用average()方法时,它都会创建一个新的文件读取实例,因此每次都会读取前8位数字。

这是我的代码:

//Code

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

public class DhruvPTheWinner{

 //Method for averaging
 public static double average()
 {
     double avg = 0.0;
     double sum = 0.0;
     double val = 0.0;
     double highest = -999.0;
     double lowest = 999.0;

     //This is how we were taught to read a file, using Try and Catch to "import" the file
     Scanner inFile = null;
     try{
            inFile = new Scanner (new File("theWinner.dat"));
        }
     catch (FileNotFoundException e){
            System.out.println("File not found");
            System.exit(0);
        }

     for(int j = 1; j <= 8; j++){
         val = inFile.nextDouble();
         //If statement to contain highest
         if(val > highest)
         {
             highest = val;
         }
         //If statement to contain lowest
         if(val < lowest)
         {
             lowest = val;
         }

         //Add the value (one of 8 #s) to the sum
         sum += val;

        }

     //Take out highest and lowest so avg only includes middle 6
     sum = (sum-highest)-lowest;
     avg = sum/6;

     return avg;
    }

 public static void main(String[] args){
        //Scores for the Contestants
        double c1Score = average();
        double c2Score = average();
        double c3Score = average();
        double c4Score = average();
        double c5Score = average();
        //Printing the scores
        System.out.printf("c1 is %.3f \nc2 is %.3f \nc3 is %.3f \nc4 is %.3f \nc5 is %.3f", c1Score, c2Score, c3Score, c4Score, c5Score);

 }
}

运行时,这是输出:

c1 is 8.767 
c2 is 8.767 
c3 is 8.767 
c4 is 8.767 
c5 is 8.767

如何解决此问题并使计算机继续读取文件,而不是重新开始?

感谢您的帮助。

最佳答案

问题是,每次调用 average 时,您都会重新打开文件(在开头)。

尝试分成两部分

1) 在main函数中:打开和关闭Scanner对象并将一行数据读入数组

2) 将数组传递给average

伪代码是

主要

for(int j = 0; j < 8; j++){
     val[j] = inFile.nextDouble();
}

average (val);

公共(public)静态双重平均(double [] arr)

for(int j = 0; j < 8; j++){
    val = arr[j];
    .... // as before
}

关于java - Java中如何连续读取一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53843841/

相关文章:

java - 从重写方法内的匿名内部类中调用 super 方法

java - 将 24 小时时间转换为秒

java - 如何为应用程序配置两个log4j

java - 检查Java中数据库表中是否存在单词

java - 从Hadoop获取用户和组列表?

java - android开发架构(android vs java web app)

java - 如何使用 bouncycaSTLe 将 X509 证书转换为 PKCS7?

java - Eclipse + Jython : Python module not found using one-to-one object factory

java - equals()方法和==相等还是不相等?

java - 是否可以更改我的包中的 log4j 级别,但不能使用例如 spring 更改 api 的 IM 中的级别