Java读取文件触发InputMismatchException,异常处理无效求解决方案
Let’s break down exactly what’s going wrong and how to fix it:
The core issue is your file contains a name with a space (Mary Bloggs), but Java’s Scanner uses whitespace (spaces, newlines, tabs) as its default delimiter. Here’s the play-by-play of the error:
- When you read the runner count with
nextInt(), the scanner leaves the newline character right after the1in its buffer. - If you use
next()to read the name, it only grabsMary(the first chunk before the space) and stops. - Next, when you try to read the birth year with
nextInt(), the scanner tries to parseBloggsas an integer—this is exactly what triggers theInputMismatchException. - This is why your output cuts off mid-name: it only read half the name before hitting the invalid data type.
The Simple Fix: Read Full Lines for Values with Spaces
Use nextLine() to capture full strings that include spaces, but make sure to consume leftover newline characters first (left behind by nextInt() calls). Here’s how to adjust your code:
// Read runner count int runnerCount = scanner.nextInt(); // Critical: Consume the newline left after the integer scanner.nextLine(); // Now read the full name (including spaces) String runnerName = scanner.nextLine(); System.out.println("The name for runner is: " + runnerName); // Proceed with other reads as normal int birthYear = scanner.nextInt(); int unknownVal1 = scanner.nextInt(); int unknownVal2 = scanner.nextInt(); // Consume newline before reading gender (or use next() since gender has no spaces) scanner.nextLine(); String gender = scanner.nextLine(); int lapCount = scanner.nextInt(); scanner.nextLine(); String parkName = scanner.nextLine(); // ... rest of your reading logic
Why Your Try-Catch Didn’t Work
Catching the exception alone doesn’t fix the root problem. The scanner would still be stuck pointing at the invalid Bloggs token, so even if you caught the error, your code couldn’t proceed correctly. Fixing the reading logic itself is the only way to resolve this.
Quick Debugging Tip
To confirm exactly what your scanner is reading, add debug prints after each operation:
String name = scanner.nextLine(); System.out.println("DEBUG: Read name -> '" + name + "'");
This will immediately show you if you’re getting partial strings or unexpected tokens.
内容的提问来源于stack exchange,提问作者Maks Drzezdzon

