Search code examples
javaregexstring-formatting

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


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!


Solution

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

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

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