Java文件io计算平均值并存储在另一个文件中

时间:2017-07-31 04:37:38

标签: java io

我很高兴知道如何解决这类问题。先感谢您。 这是问题所在。

文件的第一行包含两个整数; 记录数量考试成绩

记录数:表示文件中的记录数。 考试成绩:表示考试成绩。 该文件遵循学生姓名和成绩。 示例文件:test1.txt 包含四个记录,考试超过80.该文件遵循学生的姓名和成绩:

4  80
Mary 65.5
Jack 43.25
Harry 79.0
Mike 32.5

你必须开发以下方法的主体:

public static void readWrite(String srcfileName,String dstFileName)

从srcFileName中读取每个学生的成绩,计算他们的成绩百分比,表示如果学生通过或失败,最后报告班级平均成绩,通过的学生人数,以及未通过考试的学生人数并保存结果在dstFileName中。 上一个测试文件的输出文件应为:

Mary          81.88        passed 
Jack          54.06        passed 
Harry         98.75        passed 
Mike          40.63        failed 
class average:68.83
passed: 3
failed: 1

这是我为它写的代码,

import java.util.*;
import java.io.*;

public class Lab10Quiz {
  public static void main(String[] args) throws FileNotFoundException 
  {
    // Test cases
    readWrite("test1.txt", "out1.txt");
    readWrite("test2.txt", "out2.txt"); 
    }

/** copies the content of the srcFileName into dstFileName, and add the average of the number to the end of the dstFileName
    @param srcFileName :  souce file name contains double numbers
@param dstFileName : destination file name 
    */
    public static void readWrite(String srcFileName, String 
dstFileName) throws FileNotFoundException {
// Your code goes here
    File output = new File(dstFileName);
    PrintWriter outPut = new PrintWriter(output);

    double avg = 0;
    int count = 0;
    double tmp = 0;

    Scanner in = new Scanner(new File(srcFileName));
    while (in.hasNextDouble()) {
     tmp = in.nextDouble();
     avg += tmp;
     outPut.println(tmp);
     count ++;
    }
   avg = avg / count;
   outPut.println("Average = " + avg);
  outPut.close();
  }
}

1 个答案:

答案 0 :(得分:0)

此代码实现了您想要的目标

    double avg = 0;
    int failCounter = 0;

    String[] keywords = in.nextLine().split(" ");
    int studentNumber = Integer.parseInt(keywords[0]);
    double examValue = Double.parseDouble(keywords[1]);

    for (int i = 0; i < studentNumber; i++) {
        keywords = in.nextLine().split(" ");
        String studentName = keywords[0];
        double studentMark = Double.parseDouble(keywords[1]);
        double grade = calculateTotalGrade(studentMark, examValue);
        failCounter += (hasFailed(grade) ? 1 : 0);
        avg += grade;
        outPut.println(String.format("%s \t\t %.2f \t\t %s", studentName, grade, hasFailed(grade) ? "failed" : "passed"));
    }
    avg = avg / studentNumber;
    outPut.println("class average: " + avg);
    outPut.println("passed: " + (studentNumber - failCounter));
    outPut.println("failed: " + failCounter);

我将一些逻辑提取到以下方法中。

private static double calculateTotalGrade(double grade, double examValue) {
    return grade * 100 / examValue;
}

private static boolean hasFailed(double grade) {
    return grade < 50;
}

要回答如何解决这类问题:

  1. 寻找最简单的方法。在这种情况下,循环进行有限迭代更容易。所以我选择了for循环。
  2. 已经给出了计数器,无需重新计算。
  3. 如果您正在使用计算机,请编写一些代码并对其进行测试。
  4. 做更多这样的问题。 (如果你仔细阅读this book的第一章,这些问题就很容易了)