String.format()报错FormatFlagsConversionMismatchException

  • Post author:
  • Post category:其他


String.format()报错 FormatFlagsConversionMismatchException,一开始以为是有参数为空了,设置为非null参数后,还是同样报错.

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MainTest {
    public static void main(String[] args) {
        String msg = String.format("接口请求失败,Id:s%,code:%s,msg:%s,sub_code:%s,sub_msg:%s","chsadfa","afsdfa","afafadf",null,"asdfaf");
        log.info(msg);
    }
}

Exception in thread “main” java.util.FormatFlagsConversionMismatchException: Conversion = c, Flags = ,

at java.util.Formatter$FormatSpecifier.failMismatch(Formatter.java:4298)

at java.util.Formatter$FormatSpecifier.checkBadFlags(Formatter.java:2997)

at java.util.Formatter$FormatSpecifier.checkCharacter(Formatter.java:2974)

at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2727)

at java.util.Formatter.parse(Formatter.java:2560)

at java.util.Formatter.format(Formatter.java:2501)

at java.util.Formatter.format(Formatter.java:2455)

at java.lang.String.format(String.java:2940)

at com.rongsoft.demo.MainTest.main(MainTest.java:8)

最后检查发现是%s 写成了 s%,异常类名FormatFlagsConversionMismatchException诚不余欺也.

如果你写了5个%s,却只写了4个参数,这就会报错缺少格式化的参数(MissingFormatArgument)

Exception in thread “main” java.util.MissingFormatArgumentException: Format specifier ‘%s’

at java.util.Formatter.format(Formatter.java:2519)

at java.util.Formatter.format(Formatter.java:2455)

at java.lang.String.format(String.java:2940)

at com.rongsoft.demo.MainTest.main(MainTest.java:8)

所以参数要一一对应.



版权声明:本文为u012483153原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。