从文本文件中读取Java输入不匹配

时间:2013-02-24 20:29:45

标签: java file-io

我正在编写一个程序,该程序将从填充了学生成绩的文本文件中获取输入。这些等级得到平均值并添加到数组列表中。但是我无法获取要读取的文件。我收到的输入不匹配。我已经尝试将calcAssignmentAverage方法中的循环更改为小于15(有15个实验等级,文本文件中的第2行),但它仍然会导致输入不匹配。

文件(真实文件有16名学生,格式如下。):

Puckett, Karen
10 10 9.5 10 10 8 9.5 10 10 10 9 10 10 10 0
4 3 5 3 5 2 3 2 1.5 1 5 3.5
17.5 24 22 23.5 22 23
90 91
96

代码:

 public static void main(String[] args) throws IOException {
    final double NUM_OF_LABS = 15;
    final double NUM_OF_QUIZZES = 12;
    final double NUM_OF_PROJECTS = 6;
    final double NUM_OF_EXAMS = 2;
    final double NUM_OF_FINAL = 1;
    final double LAB_POINTS = 150;
    final double QUIZ_POINTS = 60;
    final double PROJECT_POINTS = 150;
    final double EXAM_POINTS = 200;
    final double FINAL_POINTS = 100;

    //Open input file
    File myFile = new File("scores.txt");
    if (!myFile.exists()) {
        System.out.println("The input file was not found.");
        System.exit(0);
    }

    Scanner inputFile = new Scanner(myFile);

    ArrayList<Student> studentList = new ArrayList<Student>();

    readFile(inputFile, studentList, NUM_OF_LABS, LAB_POINTS, NUM_OF_QUIZZES,
            QUIZ_POINTS, NUM_OF_PROJECTS, PROJECT_POINTS, NUM_OF_EXAMS,
            EXAM_POINTS, NUM_OF_FINAL, FINAL_POINTS);

}

public static void readFile(Scanner inputFile,
        ArrayList<Student> studentList, double NUM_OF_LABS,
        double LAB_POINTS, double NUM_OF_QUIZZES, double QUIZ_POINTS,
        double NUM_OF_PROJECTS, double PROJECT_POINTS,
        double NUM_OF_EXAMS, double EXAM_POINTS, double NUM_OF_FINAL,
        double FINAL_POINTS) {

    //read and set data for student1:
    while (inputFile.hasNext()) {
        //create a new student
        Student currentStudent = new Student();

        //read name
        String name;
        name = inputFile.nextLine();
        currentStudent.setName(name);

        //read lab average 
        double labAverage = 0;
        labAverage = calcAssignmentAverage(NUM_OF_LABS, inputFile, LAB_POINTS);
        currentStudent.setLabAverage(labAverage);


        //add currentStudent to the list
        studentList.add(currentStudent);


    }
}

public static double calcAssignmentAverage(double NUM_ASSIGNMENTS,
        Scanner inputFile, double MAX_POINTS) {

    double sum = 0;
    double average = 0;

    for (int i = 0; i < NUM_ASSIGNMENTS; i++) {
        sum = sum + inputFile.nextDouble();
    }
    average = (sum / MAX_POINTS) * 100;

    return average;
}

1 个答案:

答案 0 :(得分:0)

拜伦是对的。你晋升到下一个学生的逻辑是过早地执行。在继续循环的下一次迭代之前,您需要阅读第3到第6行,假设它们适用于同一个学生。

此外,阅读双人后,您的扫描仪不会自动前进到下一行。你需要明确地做到这一点。