Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中连续读取文件?_Java - Fatal编程技术网

如何在Java中连续读取文件?

如何在Java中连续读取文件?,java,Java,有一个文件包含5组8个数字。每组为参赛者的“分数”(共5名参赛者)。我的任务是阅读文件以获得每一组,删去最高和最低分数,然后计算每个参赛者的平均分数。 这项任务还要求我们使用一种方法来计算平均值,因此我不允许将整个程序塞进主方法 以下是供参考的数据集: 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

有一个文件包含5组8个数字。每组为参赛者的“分数”(共5名参赛者)。我的任务是阅读文件以获得每一组,删去最高和最低分数,然后计算每个参赛者的平均分数。 这项任务还要求我们使用一种方法来计算平均值,因此我不允许将整个程序塞进主方法

以下是供参考的数据集:

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);

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


谢谢您的帮助。

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

试着分成两部分

1) 在
main
功能中:打开和关闭
Scanner
对象,并将一行数据读取到数组中

2) 将数组传递到
average

伪代码将是

Main

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

average (val);

或者,您可以将
Scanner infle
声明为静态全局变量,并在调用
average()
函数之前在
main()
中仅初始化一次

这属于类范围:

public class DhruvPTheWinner{
    private static Scanner inFile=null;
把这个放在主菜单中:

     try{
            inFile = new Scanner (new File("theWinner.dat"));
        }
     catch (FileNotFoundException e){
            System.out.println("File not found");
            System.exit(0);
        }

其余部分保持不变。

我同意恐怖袋熊,你必须声明
扫描仪
超出
平均值()

我想你可以从面向对象的角度来看这个问题。你到底有什么?您有一个上下文,其中包含一些数字。另外,上下文具有基于其数据的预先计算的属性。此上下文应从文件中读取

让我们定义一个上下文,并将所有相关计算包含到其中

public class Contest {

    private static int nextId = 1;

    public final String id;
    private final double[] data;  // optionally, you can avoid storing whole array
    public final double avg;
    public final double sum;
    public final double highest;
    public final double lowest;

    public Contest(String... data) {
        id = "c" + nextId++;
        // you can calculate all this using one loop (instead of Streams)
        this.data = Arrays.stream(data).mapToDouble(Double::parseDouble).toArray();
        sum = Arrays.stream(this.data).sum();
        avg = Arrays.stream(this.data).average().orElse(Double.NaN);
        highest = Arrays.stream(this.data).max().orElse(Double.NaN);
        lowest = Arrays.stream(this.data).min().orElse(Double.NaN);
    }

}
然后,您需要一个emthod,它接受所需文件的路径并返回现有竞赛的列表:

public static List<Contest> readContests(Path path) throws IOException {
    return Files.lines(path)
                .map(line -> line.split("\\s+"))
                .map(Contest::new)
                .collect(Collectors.toList());
}

我明白你在传达什么。唯一的问题是我们还没有在课堂上从技术上学习数组,所以我们不允许在程序中使用它们。这个问题已经被Pal解决了。谢谢你告诉我如何使用阵列来解决这个问题!这是有道理的。现在,File对象属于整个类,而不仅仅是我们的主类或方法。它按预期工作。
public class Contest {

    private static int nextId = 1;

    public final String id;
    private final double[] data;  // optionally, you can avoid storing whole array
    public final double avg;
    public final double sum;
    public final double highest;
    public final double lowest;

    public Contest(String... data) {
        id = "c" + nextId++;
        // you can calculate all this using one loop (instead of Streams)
        this.data = Arrays.stream(data).mapToDouble(Double::parseDouble).toArray();
        sum = Arrays.stream(this.data).sum();
        avg = Arrays.stream(this.data).average().orElse(Double.NaN);
        highest = Arrays.stream(this.data).max().orElse(Double.NaN);
        lowest = Arrays.stream(this.data).min().orElse(Double.NaN);
    }

}
public static List<Contest> readContests(Path path) throws IOException {
    return Files.lines(path)
                .map(line -> line.split("\\s+"))
                .map(Contest::new)
                .collect(Collectors.toList());
}
List<Contest> contests = readContests(Paths.get("theWinner.dat"));
contests.forEach(contest -> System.out.format(Locale.US, "%s is %.3f\n", contest.id, contest.avg));
c1 is 8.763
c2 is 7.000
c3 is 8.000
c4 is 8.356
c5 is 7.025