当前位置: 动力学知识库 > 问答 > 编程问答 >

Java Input Mismatch Reading from Text File

问题描述:

I'm writing a program that will take input from a text file filled with students' grades. These grades get averaged and added to an array list. I'm having trouble getting the file to be read in however. I'm receiving an input mismatch. I've tried changing the loop in my calcAssignmentAverage method to less than 15 (there are 15 lab grades, the 2nd line in the text file), but it still gives an input mismatch.

File (real file has 16 students in the following format.):

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

Code:

 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;

}

网友答案:

Byron is right. Your logic to advance to the next student is executing prematurely. You need to read lines 3 through 6 before you continue to the next iteration of the loop, assuming that they apply to the same student.

Also, after reading a double, your Scanner will not automatically advance to the next line. You need to do that explicitly.

分享给朋友:
您可能感兴趣的文章:
随机阅读: