2013-02-24 96 views
0

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

文件(真正的文件有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

您的代码使用不包含的学生类 – aditsu 2013-02-24 20:35:32

+0

对不起,但这是第三次阅读您的问题,但我不知道究竟需要什么以及您的错误。 请指定更多 – Azad 2013-02-24 20:43:59

+0

样本文件中第二行之后的行号(数字)是什么?目前你只使用第二行,但如果while循环占用所有行,则它将无法正常工作,因为它假设新学生位于第3行。 – Byron 2013-02-24 20:55:28

回答

0

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

此外,读取双倍数据后,扫描仪不会自动前进到下一行。你需要明确地做到这一点。

+0

谢谢,点击答案中的某些内容,并添加了inputFile.nextLine() ; currentStudent被添加到列表后的一行。现在它工作了! – user2105302 2013-02-24 22:43:16