【发布时间】:2017-07-31 04:37:38
【问题描述】:
如果知道如何解决此类问题,我将不胜感激。先感谢您。 这是问题。
文件的第一行包含两个整数; 考试成绩记录数
number-of-records :表示文件中的记录数。 考试等级:表示考试的等级。 该文件后跟学生姓名和成绩。 示例文件:test1.txt 包含4条记录,考试满分80分。文件后面是学生的姓名和年级:
4 80
Mary 65.5
Jack 43.25
Harry 79.0
Mike 32.5
您必须开发以下方法的主体:
public static void readWrite(String srcfileName, String dstFileName)
从 srcFileName 读取每个学生的成绩,计算他们的成绩百分比,指示学生是否通过,最后报告班级平均分,通过的学生人数,考试不及格的学生人数并保存结果在 dst 文件名中。 上一个测试文件的输出文件应该是:
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();
}
}
【问题讨论】:
-
非常有趣。你也有问题吗?
-
由于您的输入行包含不同的数据类型,要么提示每个数据类型,要么更好的方法是读取该行,然后按空格分割
-
作为初级程序员,我认为将代码分解成小部分来处理任务是解决问题的好方法。我首先会读取文件,像@ScaryWombat 建议的那样在空间上拆分,然后将文件信息保存到某种类型的数据结构中(
List或Array)。然后,我将遍历数据结构并进行任何计算并将该信息保存到类似的数据结构中。最后,我会使用我的数据结构的信息写入文件。