“IllegalFormatConversionException: d != java.lang.String” when padding number with 0s?

不羁的心 提交于 2019-12-01 14:32:51

问题


I had a perfectly working code yesterday, in the exact form of:

int lastRecord = 1;
String key = String.format("%08d", Integer.toString(lastRecord));

Which would pad it nicely to 00000001.

Now I kicked it up a notch with twoKeyChar getting a string from a table and lastRecord getting an int from a table.

As you can see the concept is essentially the same - I convert an int to a string and try to pad it with 0s; however, this time I get the following error:

java.util.IllegalFormatConversionException: d != java.lang.String

The code is below:

String newPK = null;
String twoCharKey = getTwoCharKey(tablename);
if (twoCharKey != null) {
     int lastRecord = getLastRecord(tablename);
     lastRecord++;
     //The println below outputs the correct values: "RU" and 11. 
     System.out.println("twocharkey:"+twoCharKey+"record:"+lastRecord+"<");
     //Now just to make it RU00000011
     newPK = String.format("%08d", Integer.toString(lastRecord));
     newPK = twoCharKey.concat(newPK);
}

I feel like I must have typed something wrong, because there is no reason for it to break since the last time when it worked. Any help/hint is appreciated! Thank You!


回答1:


You don't need the Integer.toString():

 newPK = String.format("%08d", lastRecord);

String.format() will do the conversion and the padding.



来源:https://stackoverflow.com/questions/10903579/illegalformatconversionexception-d-java-lang-string-when-padding-number-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!