# java.util.IllegalFormatConversionException：d != java.lang.String

- **ID:** `java/illegal-format-conversion`
- **领域:** java
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

格式说明符（例如用于整数的 %d）与不兼容类型的参数（例如 String）一起使用，导致通过 String.format 或 PrintStream.printf 格式化字符串时发生运行时异常。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Java 8 | active | — | — |
| Java 11 | active | — | — |
| Java 17 | active | — | — |
| Java 21 | active | — | — |

## 解决方案

1. ```
   确保参数类型与格式说明符匹配。对于 %d，传递整数：`String.format("Value: %d", 42)` 而不是 `String.format("Value: %d", "42")`。如有必要，使用 Integer.parseInt() 将字符串转换为整数。
   ```
2. ```
   为参数类型使用正确的格式说明符：字符串用 %s，浮点数用 %f，整数用 %d。示例：`String.format("Name: %s, Age: %d", name, age)`
   ```
3. ```
   如果参数可以是多种类型，使用条件语句应用正确的格式说明符：`String.format(arg instanceof Integer ? "%d" : "%s", arg)`
   ```

## 无效尝试

- **Change the format specifier to %s to accept any type.** — 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. (60% 失败率)
- **Use `String.valueOf(arg)` to convert the argument before formatting.** — 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. (90% 失败率)
- **Catch the exception and retry with a different format.** — This only masks the error; the underlying type mismatch remains and may cause further issues in downstream logic. (70% 失败率)
