java
type_error
ai_generated
true
java.util.InputMismatchException
ID: java/inputmismatchexception
88%Fix Rate
86%Confidence
1Evidence
2023-06-18First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Java 8 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
Root Cause
The input token does not match the expected type when using a Scanner, often due to incorrect locale or unexpected data format.
generic中文
使用 Scanner 时输入令牌与期望类型不匹配,通常由于区域设置错误或数据格式意外。
Official Documentation
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/InputMismatchException.htmlWorkarounds
-
90% success Use hasNextInt() before nextInt(): 'if (scanner.hasNextInt()) { int value = scanner.nextInt(); } else { scanner.next(); /* consume invalid token */ }'
Use hasNextInt() before nextInt(): 'if (scanner.hasNextInt()) { int value = scanner.nextInt(); } else { scanner.next(); /* consume invalid token */ }' -
85% success Set the locale to match the input format: 'scanner.useLocale(Locale.US);' for decimal numbers with dot separator.
Set the locale to match the input format: 'scanner.useLocale(Locale.US);' for decimal numbers with dot separator.
中文步骤
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.
Dead Ends
Common approaches that don't work:
-
60% fail
Setting the locale to US (Locale.US) may not fix the issue if the input contains non-numeric characters.
-
70% fail
Using next() instead of nextInt() and then manually parsing can still throw NumberFormatException if the string is malformed.