2017-05-03 78 views
0

因此,我们希望应用程序允许用户输入学生的姓名和成绩,并提示用户输入要创建的文件的名称以及要输入的学生数量(每个学生1个等级)。然后该程序将获取所有成绩并对其进行平均。问题是它没有读取文件,总是给我们-0.0的平均值。Java文件问题

`

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."); 
    } 

} 

} `

+1

尝试调用'ad.close();''之前'读取(fd);' – nandsito

+0

也许问题是文件的内容;不能说,因为你没有分享它。 –

+0

我想尝试使用这里提到的扫描仪:[使用扫描仪读取.txt文件](http://stackoverflow.com/questions/13185727/reading-a-txt-file-using-scanner-class-in- JAVA) –

回答

3

您正在尝试从文件中读取您已经关闭了作家之前。

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

作为一个侧面说明,考虑你这个语句对完成的事情:

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

while是不必要的。 for陈述重复了舒适麻木的学生。

还要注意两者之间的差异。通常,在遍历数字时,使用'<','< =','>'或'> ='比'=='或'!='更安全。否则,如果您在平等条件之前通过端点,则它将继续愉快地继续结束。

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