String.format()error:java.util.MissingFormatArgumentException

时间:2016-12-23 17:25:18

标签: java

我收到此错误:

Caused by: java.util.MissingFormatArgumentException: Format specifier: &
at java.util.Formatter$FormatToken.unknownFormatConversionException(Formatter.java:1399)
at java.util.Formatter$FormatToken.checkFlags(Formatter.java:1336)
at java.util.Formatter.transform(Formatter.java:1442)
at java.util.Formatter.doFormat(Formatter.java:1081)
at java.util.Formatter.format(Formatter.java:1042)
at java.util.Formatter.format(Formatter.java:1011)
at java.lang.String.format(String.java:1554)
at java.lang.String.format(String.java:1528)

在这行代码中:

query = String.format(GMAP_QUERY, location, location);

变量:

private String location = "12.38484,55.43845";

static final String GMAP_QUERY = "staticmapcenter=%s&zoom=13&size=300x100&maptype=roadmap%20&markers=color:red%7C%s&style=feature:poi|element:labels|visibility:off";

为什么会抛出异常? Format specifier: &是什么意思?

3 个答案:

答案 0 :(得分:2)

您的网址(%20)&maptype=roadmap%20和(%7C)&markers=color:red%7C看起来只是一个空格,您已经拥有&style=feature:poi|element:labels|visibility:off

然后解决这些问题,并使用URLEncoder对您需要格式化的字符串进行编码。

String fmt = "staticmapcenter=%s&zoom=13&size=300x100&maptype=roadmap&markers=color:red|%s&style=feature:poi|element:labels|visibility:off";
String path = URLEncoder.encode(String.format(fmt, "s1", "s2"));

这使得staticmapcenter%3Ds1%26zoom%3D13%26size%3D300x100%26maptype%3Droadmap%26markers%3Dcolor%3Ared%7Cs2%26style%3Dfeature%3Apoi%7Celement%3Alabels%7Cvisibility%3Aoff

但是,你可能正在寻找这个。

String location = "12.38484,55.43845";
String fmt = "staticmap?center=%s&zoom=13&size=300x100&maptype=roadmap&markers=color:red|%s&style=feature:poi|element:labels|visibility:off";
String path = String.format(fmt, location, location);
System.out.print("http://maps.googleapis.com/maps/api/" + path);

http://maps.googleapis.com/maps/api/staticmap?center=12.38484,55.43845&zoom=13&size=300x100&maptype=roadmap&markers=color:red|12.38484,55.43845&style=feature:poi|element:labels|visibility:off

答案 1 :(得分:1)

你需要逃避不需要的%。否则String会将其作为参数(缺失)。 要逃避单个(未重复的)百分号,您需要在其后面添加另一个百分比字符,即。 %%。

值得看看这个: 来自Oracle Java: Literal percent sign in printf statement

https://docs.oracle.com/javase/tutorial/java/data/strings.html和Java跟踪

答案 2 :(得分:1)

问题在于强调部分:

"staticmapcenter=%s&zoom=13&size=300x100&maptype=roadmap%20&markers=color:red%7C%s&style=feature:poi|element:labels|visibility:off"

URL编码中使用的%也在String.format中被解析为格式化程序。他们需要逃脱。例外是抱怨它并不了解%20&的含义。