gpt4 book ai didi

Java 文件问题

转载 作者:行者123 更新时间:2023-12-01 20:26:51 24 4
gpt4 key购买 nike

因此,我们希望有一个应用程序允许用户输入学生的姓名和成绩,系统应提示用户输入要创建的文件的名称以及要输入的学生人数(每个学生 1 个年级)。然后该程序会获取所有成绩并计算平均值。问题是它没有读取文件并且总是给我们平均值 -0.0。

`

public static void main(String[] args) throws IOException {

System.out.println("What is the name of the file you would like to create?");
filename = p.next();

File fd = new File(filename + ".txt");
fd.createNewFile();
students(fd);
}

public static void students(File fd) throws IOException {
int numbstudents;
FileWriter ap = new FileWriter(fd, true);
BufferedWriter ad = new BufferedWriter(ap);

System.out.println("How many students would you like to add?");
numbstudents = p.nextInt();
int i = 0;
while (i != numbstudents) {
for (i = 0; i < numbstudents; i++) {
System.out.println("What is the name of student number " + i + " ?");
String name = p.next();
ad.write(name);
ad.newLine();
System.out.println("What grade did student number " + i + " acheive?");
String a = f.next();
ad.write(a);
ad.newLine();

}
}

read(fd);
ad.close();
}

public static void read(File fd) throws FileNotFoundException {

int counter = 0;
FileReader h;
BufferedReader g;
String test;
double average, total = 0;
int number = 0;
int i = 0;
try {
h = new FileReader(fd);
g = new BufferedReader(h);
while ((test = g.readLine()) != null) {
number += 1;
System.out.println(test);
counter = counter + 1;
i = counter % 2;
if (i == 0) {
total += Double.parseDouble(test);
}

}
average = total / (number - 1);
System.out.println("The students average is: " + average);

g.close();
fd.delete();
} catch (FileNotFoundException e) {
System.out.println("File could not be found.");
} catch (IOException e) {
System.out.println("Your file could not be read.");
}

}

}`

最佳答案

您正在尝试在关闭编​​写器之前读取文件。

close() 调用包括将缓冲数据刷新到磁盘。您正在将数据刷新到磁盘之前进行读取。

作为旁注,请考虑一下您使用这对语句要完成的任务:

while (i != numbstudents) {
for (i = 0; i < numbstudents; i++) {

while 是不必要的。 for 语句迭代了那些 NumPy 的学生。

还要注意两者之间条件的差异。一般来说,在迭代数字时,使用“<”、“<=”、“>”或“>=”比“==”或“!=”更安全。否则,如果您在相等条件之前经过端点,它将继续愉快地越过终点。

最后,考虑使用描述性动词短语来命名您的方法。这将帮助您将大问题分解为小问题。例如,您可以使用一个名为 inputStudents() 的方法,该方法读取输入并创建并关闭文件,该方法在另一个方法 printAverageOfStudents() 之前调用读取文件并计算平均值。

关于Java 文件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43768134/

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