gpt4 book ai didi

java - 在java中使用文件流时没有得到任何输出

转载 作者:行者123 更新时间:2023-12-01 18:24:17 25 4
gpt4 key购买 nike

我已经在编程作业的这一部分上停留了一段时间,我似乎不明白出了什么问题。我应该使用扫描仪从输入文件中获取成绩并将其放入数组(而不是 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();

}

}

最佳答案

这是一个无限循环,因为它不会推进文件指针:

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

该行还包含一个错误:

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

应该是

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

关于java - 在java中使用文件流时没有得到任何输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60253104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com