Java string.format()只有一半工作

时间:2015-08-19 16:09:26

标签: java string format

我正在尝试使用string.format()构造一个字符串,但它在中途停止工作(刚刚结束)。

private String constructMessage(String messageType, int messageCode,Position location) {
    double lat = location.getLat();
    double lon = location.getLon();
    double ele = location.getEle();
    double speed = 0.0;
    double heading = 0.0;

    String msg = "$PNGVEST," + messageType + "," + VEST_ID + ","
            + System.currentTimeMillis() + "," + lat + "," + lon + "," + ele
            + "," + speed + "," + heading + "," + messageCode;

    String test = String.format("$PNGVEST,%s,%d,%d,%f,%f,%f,$f,$f,$d",
            messageType, VEST_ID, System.currentTimeMillis(), lat, lon, ele,
            speed, heading, messageCode);

    System.out.println(msg);
    System.out.println(test);
    return msg;
}

当我运行上面的代码时,我得到以下输出:

$PNGVEST,LOCATION,1,1439998967553,51.558641765246364,-3.043043462354341,-1.0,0.0,0.0,0
$PNGVEST,LOCATION,1,1439998967553,51.558642,-3.043043,-1.000000,$f,$f,$d
$PNGVEST,LOCATION,1,1439998968553,51.55862560874394,-3.043027770590568,-1.0,0.0,0.0,0
$PNGVEST,LOCATION,1,1439998968553,51.558626,-3.043028,-1.000000,$f,$f,$d

为什么不格式化最后3个变量?

2 个答案:

答案 0 :(得分:4)

你用最后3个变量做了拼写错误。您注意到$f$d而不是%f%d

应该是:

String test = String.format("$PNGVEST,%s,%d,%d,%f,%f,%f,%f,%f,%d",
        messageType, VEST_ID, System.currentTimeMillis(), lat, lon, ele,
        speed, heading, messageCode);

而不是

String.format("$PNGVEST,%s,%d,%d,%f,%f,%f,$f,$f,$d", ...);

答案 1 :(得分:0)

尝试改变,

String test = String.format("$PNGVEST,%s,%d,%d,%f,%f,%f,$f,$f,$d",
        messageType, VEST_ID, System.currentTimeMillis(), lat, lon, ele,
        speed, heading, messageCode);

String test = String.format("$PNGVEST,%s,%d,%d,%f,%f,%f,%f,%f,%d",
        messageType, VEST_ID, System.currentTimeMillis(), lat, lon, ele,
        speed, heading, messageCode);