读取TXT文件时遭遇InputMismatchException问题求助
我编写了一个Java程序,预期实现读取TXT文件、执行计算逻辑后输出至另一个文件的功能,但运行时出现InputMismatchException,无法定位问题根源。尝试过类型转换、调整输入文件字段顺序,问题仍未解决,恳请帮忙排查。
原始代码
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { // Create an ArrayList to store the students ArrayList<Student> studentList = new ArrayList<>(); // Read data from input file and create Student objects try { Scanner input = new Scanner(new File("C:\\Users\\BP\\IdeaProjects\\Input.txt")); while (input.hasNext()) { String SID = input.next(); int S1 = input.nextInt(); int S2 = input.nextInt(); int S3 = input.nextInt(); String name = input.next(); int totalHr = input.nextInt(); double GPA = input.nextDouble(); Student student = new Student(SID, name, S1, S2, S3, totalHr, GPA); studentList.add(student); } input.close(); } catch (FileNotFoundException e) { System.err.println("Input file not found."); System.exit(1); } // Calculate the percentage score and assign letter grades for each student for (Student student : studentList) { student.calculatePercentageScore(); student.calculateLetterGrade(); } // Print student information including % score and grades for (Student student : studentList) { student.printStudentInfo(); } // Delete students with specified IDs deleteStudent(studentList, "42P4"); deleteStudent(studentList, "45A3"); // List the ArrayList after deleting students System.out.println("\nAfter deleting students:"); for (Student student : studentList) { student.printStudentInfo(); } // Add new students to the ArrayList Student student1 = new Student("67T4", "Clouse B",80, 75, 98, 102, 3.65); Student student2 = new Student("45P5", "Garrison J",75, 78, 72, 39, 1.85); Student student3 = new Student("89P0", "Singer A",85, 95, 99, 130, 3.87); studentList.add(student1); studentList.add(student2); studentList.add(student3); // Calculate grades and sort the ArrayList by % score (lower to higher) bubbleSort(studentList); // Print the sorted ArrayList System.out.println("\nAfter sorting by % score (lower to higher):"); for (Student student : studentList) { student.printStudentInfo(); } } // Function to delete a student from the ArrayList by StudentID public static void deleteStudent(ArrayList<Student> studentList, String studentID) { for (int i = 0; i < studentList.size(); i++) { Student student = studentList.get(i); if (student.getStudentID().equals(studentID)) { studentList.remove(i); System.out.println("Student with ID " + studentID + " has been deleted."); break; // No need to continue searching } } } // Function to sort the ArrayList by % score (lower to higher) public static void bubbleSort(ArrayList<Student> studentList) { int n = studentList.size(); boolean swapped; do { swapped = false; for (int i = 0; i < n - 1; i++) { if (studentList.get(i).getPercentageScore() < studentList.get(i + 1).getPercentageScore()) { // Swap the students Student temp = studentList.get(i); studentList.set(i, studentList.get(i + 1)); studentList.set(i + 1, temp); swapped = true; } } } while (swapped); } } class Student { private String studentID; private int test1, test2, test3; private String name; private int percentageScore; private char letterGrade; private int totalHr; private double GPA; public Student( String studentID, String name,int test1, int test2, int test3, int totalHour, double GPA) { this.test1 = test1; this.test2 = test2; this.test3 = test3; this.studentID = studentID; this.name = name; this.totalHr=totalHr; this.GPA=GPA; } public void calculatePercentageScore() { percentageScore = (int)((test1 + test2 + test3) / 3.0); } public void calclateClass() { if(totalHr >= 1 && totalHr <=30) { } } public void calculateLetterGrade() { if (percentageScore >= 90) { letterGrade = 'A'; } else if (percentageScore >= 80) { letterGrade = 'B'; } else if (percentageScore >= 70) { letterGrade = 'C'; } else if (percentageScore >= 60) { letterGrade = 'D'; } else { letterGrade = 'F'; } } public void printStudentInfo() { System.out.println("Student ID: " + studentID); System.out.println("Name: " + name); System.out.println("Test 1: " + test1 + ", Test 2: " + test2 + ", Test 3: " + test3); System.out.println("Percentage Score: " + percentageScore); System.out.println("Letter Grade: " + letterGrade); System.out.println("Total hours: " +totalHr); System.out.println("GPA: " + GPA); } public String getStudentID() { return studentID; } public int getPercentageScore() { return percentageScore; } }
输入文件内容
Student ID Student Name Test 1 Test 2 Test 3 Total Hr GPA 45A3 Jones_H_A 86 88 95 98 3.42 34K5 Horner_M 67 75 23 17 1.95 56J8 Gach_T_A 75 85 90 60 3.75 34U8 Hunter_C 100 50 75 75 2.60 42P4 Hinrichs_S 85 75 65 52 3.29 78T6 Johnson_K 80 78 89 15 2.00 44L2 Levitte_H 56 66 99 100 2.35 88I9 Garner_J 95 92 98 110 3.89
问题根源与修复方案
1. 字段读取顺序与输入文件完全不匹配
代码中读取顺序为:SID → 测试1 → 测试2 → 测试3 → 姓名 → 总学时 → GPA,但输入文件实际顺序是:Student ID → 姓名 → 测试1 → 测试2 → 测试3 → 总学时 → GPA。当代码尝试用input.nextInt()读取姓名字段时,自然抛出类型不匹配异常。
修复:调整读取顺序与输入文件一致,或读取整行后拆分字段(更鲁棒)。
2. 未跳过文件表头
输入文件第一行是表头文本,代码直接开始读取,会把"Student"当作学生ID,后续尝试读取数字时必然失败。
修复:调用input.nextLine()跳过表头行。
3. Student构造函数赋值错误
构造函数中this.totalHr=totalHr;是将成员变量赋值给自己,正确写法应为this.totalHr=totalHour;,否则totalHr始终为默认值0。
修复:修正构造函数的赋值语句。
4. 冒泡排序逻辑颠倒
代码中判断条件为studentList.get(i).getPercentageScore() < studentList.get(i + 1).getPercentageScore()时交换,实际会生成降序列表,但注释要求按升序排列。
修复:将判断条件改为studentList.get(i).getPercentageScore() > studentList.get(i + 1).getPercentageScore()。
修正后的完整代码
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { ArrayList<Student> studentList = new ArrayList<>(); try { Scanner input = new Scanner(new File("C:\\Users\\BP\\IdeaProjects\\Input.txt")); // 跳过表头行 input.nextLine(); while (input.hasNextLine()) { String line = input.nextLine().trim(); // 跳过空行 if (line.isEmpty()) continue; // 按任意空白字符拆分字段 String[] fields = line.split("\\s+"); // 匹配输入文件顺序读取字段 String sid = fields[0]; String name = fields[1]; int test1 = Integer.parseInt(fields[2]); int test2 = Integer.parseInt(fields[3]); int test3 = Integer.parseInt(fields[4]); int totalHr = Integer.parseInt(fields[5]); double gpa = Double.parseDouble(fields[6]); Student student = new Student(sid, name, test1, test2, test3, totalHr, gpa); studentList.add(student); } input.close(); } catch (FileNotFoundException e) { System.err.println("输入文件未找到"); System.exit(1); } catch (NumberFormatException e) { System.err.println("输入文件数据格式错误:" + e.getMessage()); e.printStackTrace(); } // 计算成绩与等级 for (Student student : studentList) { student.calculatePercentageScore(); student.calculateLetterGrade(); } // 打印初始列表 System.out.println("=== 初始学生列表 ==="); for (Student student : studentList) { student.printStudentInfo(); } // 删除指定学生 deleteStudent(studentList, "42P4"); deleteStudent(studentList, "45A3"); System.out.println("\n=== 删除指定学生后 ==="); for (Student student : studentList) { student.printStudentInfo(); } // 添加新学生 Student student1 = new Student("67T4", "Clouse_B", 80, 75, 98, 102, 3.65); Student student2 = new Student("45P5", "Garrison_J", 75, 78, 72, 39, 1.85); Student student3 = new Student("89P0", "Singer_A", 85, 95, 99, 130, 3.87); studentList.add(student1); studentList.add(student2); studentList.add(student3); // 升序排序 bubbleSort(studentList); System.out.println("\n=== 按百分比成绩升序排序后 ==="); for (Student student : studentList) { student.printStudentInfo(); } } // 使用Iterator删除元素,避免索引异常 public static void deleteStudent(ArrayList<Student> studentList, String studentID) { Iterator<Student> iterator = studentList.iterator(); while (iterator.hasNext()) { Student student = iterator.next(); if (student.getStudentID().equals(studentID)) { iterator.remove(); System.out.println("已删除ID为 " + studentID + " 的学生"); break; } } } // 修正为升序排序 public static void bubbleSort(ArrayList<Student> studentList) { int n = studentList.size(); boolean swapped; do { swapped = false; for (int i = 0; i < n - 1; i++) { if (studentList.get(i).getPercentageScore() > studentList.get(i + 1).getPercentageScore()) { Student temp = studentList.get(i); studentList.set(i, studentList.get(i + 1)); studentList.set(i + 1, temp); swapped = true; } } } while (swapped); } } class Student { private String studentID; private int test1, test2, test3; private String name; private int percentageScore; private char letterGrade; private int totalHr; private double GPA; // 修正构造函数赋值错误 public Student(String studentID, String name, int test1, int test2, int test3, int totalHour, double GPA) { this.test1 = test1; this.test2 = test2; this.test3 = test3; this.studentID = studentID; this.name = name; this.totalHr = totalHour; this.GPA = GPA; } public void calculatePercentageScore() { percentageScore = (int) ((test1 + test2 + test3) / 3.0); } public void calculateLetterGrade() { if (percentageScore >= 90) { letterGrade = 'A'; } else if (percentageScore >= 80) { letterGrade = 'B'; } else if (percentageScore >= 70) { letterGrade = 'C'; } else if (percentageScore >= 60) { letterGrade = 'D'; } else { letterGrade = 'F'; } } public void printStudentInfo() { System.out.println("学生ID: " + studentID); System.out.println("姓名: " + name); System.out.println("测试1: " + test1 + ", 测试2: " + test2 + ", 测试3: " + test3); System.out.println("百分比成绩: " + percentageScore); System.out.println("等级: " + letterGrade); System.out.println("总学时: " + totalHr); System.out.println("GPA: " + GPA); System.out.println("---------------------------"); } public String getStudentID() { return studentID; } public int getPercentageScore() { return percentageScore; } }
内容的提问来源于stack exchange,提问作者Bethane

