java
type_error
ai_generated
true
java.util.InputMismatchException
ID: java/inputmismatchexception
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.
官方文档
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/InputMismatchException.html解决方案
-
Use hasNextInt() before nextInt(): 'if (scanner.hasNextInt()) { int value = scanner.nextInt(); } else { scanner.next(); /* consume invalid token */ }' -
Set the locale to match the input format: 'scanner.useLocale(Locale.US);' for decimal numbers with dot separator.
无效尝试
常见但无效的做法:
-
60% 失败
Setting the locale to US (Locale.US) may not fix the issue if the input contains non-numeric characters.
-
70% 失败
Using next() instead of nextInt() and then manually parsing can still throw NumberFormatException if the string is malformed.