You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java读取文件触发InputMismatchException,异常处理无效求解决方案

Fixing the InputMismatchException When Reading Names with Spaces from a File

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:

  1. When you read the runner count with nextInt(), the scanner leaves the newline character right after the 1 in its buffer.
  2. If you use next() to read the name, it only grabs Mary (the first chunk before the space) and stops.
  3. Next, when you try to read the birth year with nextInt(), the scanner tries to parse Bloggs as an integer—this is exactly what triggers the InputMismatchException.
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:54:03