java type_error ai_generated true

java.util.InputMismatchException

ID: java/inputmismatchexception

其他格式: JSON · Markdown 中文 · English
88%修复率
86%置信度
1证据数
2023-06-18首次发现

版本兼容性

版本状态引入弃用备注
Java 8 active
Java 11 active
Java 17 active
Java 21 active

根因分析

使用 Scanner 时输入令牌与期望类型不匹配,通常由于区域设置错误或数据格式意外。

English

The input token does not match the expected type when using a Scanner, often due to incorrect locale or unexpected data format.

generic

官方文档

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/InputMismatchException.html

解决方案

  1. Use hasNextInt() before nextInt(): 'if (scanner.hasNextInt()) { int value = scanner.nextInt(); } else { scanner.next(); /* consume invalid token */ }'
  2. Set the locale to match the input format: 'scanner.useLocale(Locale.US);' for decimal numbers with dot separator.

无效尝试

常见但无效的做法:

  1. 60% 失败

    Setting the locale to US (Locale.US) may not fix the issue if the input contains non-numeric characters.

  2. 70% 失败

    Using next() instead of nextInt() and then manually parsing can still throw NumberFormatException if the string is malformed.