Java作业程序抛出InputMismatchException错误,求修复方案
java.util.InputMismatchException in Your Java File Reading Code Hey Jacob, let’s break down that frustrating InputMismatchException you’re getting when running your school assignment code. This error is super common with file reading using Scanner, and it almost always comes down to one simple issue: your code is expecting a certain data type (like an int for sales totals) but is hitting something else in the file instead.
Common Causes & Fixes
Mismatched data order in code vs. file
Your file has teacher last names, class identifiers, and sales numbers—but if your code tries to read anintfirst (before the text values), it’ll throw this exception immediately. For example, if your file looks like:Doe 9thGrade 1200
Smith 10thGrade 1500
Your code needs to read the two string values first, then the integer. Here’s a corrected snippet to match this format:try (Scanner fileScanner = new Scanner(new File("sales-data.txt"))) { while (fileScanner.hasNext()) { // Read text values first String teacherLastName = fileScanner.next(); String className = fileScanner.next(); // Then read the integer sales value int totalSales = fileScanner.nextInt(); // Add your logic here to store data in your quantity array or other structures System.out.printf("%s's class %s sold $%d%n", teacherLastName, className, totalSales); } } catch (FileNotFoundException e) { System.err.println("Couldn't find the file: " + e.getMessage()); } catch (InputMismatchException e) { // Print the problematic line to debug System.err.println("Invalid data line: " + fileScanner.nextLine()); }Invalid characters in numeric fields
If your sales numbers have commas (like1,200instead of1200) or non-digit characters,nextInt()will fail. You’ll need to either clean up the file to remove those characters, or modify your code to read the value as a string first, strip non-digits, then convert toint:// Example for handling commas in sales numbers String salesStr = fileScanner.next().replace(",", ""); int totalSales = Integer.parseInt(salesStr);Unexpected blank lines or extra whitespace
Blank lines in the file can throw offScanner’s reading flow. You can add a check to skip empty lines:while (fileScanner.hasNextLine()) { String line = fileScanner.nextLine().trim(); if (line.isEmpty()) continue; // Skip blank lines // Use a separate scanner for each line to avoid mismatches Scanner lineScanner = new Scanner(line); String teacherLastName = lineScanner.next(); String className = lineScanner.next(); int totalSales = lineScanner.nextInt(); lineScanner.close(); // Process data... }
Quick Debug Tip
Add a catch block specifically for InputMismatchException that prints the line causing the issue. This will tell you exactly which part of the file is breaking your code—super helpful for fixing typos or formatting errors you might have missed.
内容的提问来源于stack exchange,提问作者Jacob Roth

