You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一行中同时使用字符串格式化%s与%符号?

解决Java String.format中%符号引发的格式转换异常

在Java的String.format()方法里,%是格式转换标记的起始字符。你写的格式化字符串"Your name is %s, 100%point"中,%p会被识别成一个格式转换符,但Java并没有定义%p这类转换规则,因此抛出UnknownFormatConversionException。

要在格式化结果中输出单个%字符,需要用**两个连续的%(%%)**做转义处理,修改后的代码如下:

String format = "Your name is %s, 100%%point";
String name = String.format(format, "Harry");

System.out.print(name); // 输出:Your name is Harry, 100%point

Java的格式化规则中,%%会被解析为一个普通的%字符,不会触发格式转换逻辑,这样就能正常得到你期望的输出结果。

内容的提问来源于stack exchange,提问作者GHH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 01:05:22