[在Java中使用文件流时未获得任何输出

问题描述 投票:0回答:1

我已经在编程作业的这一部分上停留了一段时间,我似乎无法理解问题所在。我应该使用扫描仪从输入文件中获取成绩并将其放入数组(而不是ArrayList)中。然后,它应该计算平均值,最大值和最小值,然后将其打印到新的单独文本文件中。该程序运行没有错误,但是我的输出文件中没有输出。我在想这个吗?麻烦的代码,请稍后再解决。

import java.util.Scanner;
import java.io.*;
public class GradeStatistics {

public static void main(String[] args) throws FileNotFoundException {
    Scanner scanNum = new Scanner(new File("grades.txt"));
    double total = 0;
    int numStudents = 0;

    //traverse the file, counting the number of lines and save into numStudents
    while(scanNum.hasNextInt())
    {
        numStudents += 1;
    }

    int grades[] = new int[numStudents];    //create grades array

    Scanner scan2 = new Scanner("grades.txt");

    //populate the array
    for(int i = 0; i < grades.length; i++)
    {
        grades[i] = scan2.nextInt();
    }

    int max = grades[0];
    int min = grades[0];

    //find the max and min
    for(int i = 0; i < grades.length; i++)
    {
        total = total + grades[i];
        if(grades[i] > max)
        max = grades[i];
    }
    for(int i = 0; i < grades.length; i++)
    {
        if(grades[i] < min)
            min = grades[i];
    }
    double average = total / grades.length;     //calculate the average

    //create a new file "results.txt" to print our results
    FileOutputStream f = new FileOutputStream("results.txt");
    System.setOut(new PrintStream(f));
    System.out.printf("The average is: %.2f\n", average);
    System.out.println("The minimum is: " + min);
    System.out.println("The maximum is: " + max);
    scan2.close();
    scanNum.close();

}

}

java
1个回答
0
投票

这是一个无休止的循环,因为它没有推进文件指针:

while(scanNum.hasNextInt())
{
    numStudents += 1;
}

此行还包含错误:

Scanner scan2 = new Scanner("grades.txt");

应该是

Scanner scan2 = new Scanner(new File("grades.txt"));
© www.soinside.com 2019 - 2024. All rights reserved.