java.util.IllegalFormatConversionException:d != java.lang.String
java.util.IllegalFormatConversionException: d != java.lang.String
ID: java/illegal-format-conversion
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Java 8 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
根因分析
格式说明符(例如用于整数的 %d)与不兼容类型的参数(例如 String)一起使用,导致通过 String.format 或 PrintStream.printf 格式化字符串时发生运行时异常。
English
A format specifier (e.g., %d for integer) is used with an argument of an incompatible type (e.g., String), causing a runtime exception when formatting strings via String.format or PrintStream.printf.
官方文档
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/IllegalFormatConversionException.html解决方案
-
确保参数类型与格式说明符匹配。对于 %d,传递整数:`String.format("Value: %d", 42)` 而不是 `String.format("Value: %d", "42")`。如有必要,使用 Integer.parseInt() 将字符串转换为整数。 -
为参数类型使用正确的格式说明符:字符串用 %s,浮点数用 %f,整数用 %d。示例:`String.format("Name: %s, Age: %d", name, age)` -
如果参数可以是多种类型,使用条件语句应用正确的格式说明符:`String.format(arg instanceof Integer ? "%d" : "%s", arg)`
无效尝试
常见但无效的做法:
-
Change the format specifier to %s to accept any type.
60% 失败
While %s works for strings, it produces the string representation of the object, which may not match the desired numeric formatting (e.g., padding, precision). This changes the output format unintentionally.
-
Use `String.valueOf(arg)` to convert the argument before formatting.
90% 失败
If the argument is not a string, String.valueOf will still produce a string, but the format specifier %d will still expect an integer, causing the same exception.
-
Catch the exception and retry with a different format.
70% 失败
This only masks the error; the underlying type mismatch remains and may cause further issues in downstream logic.