2012-06-05 440 views
5

昨天我有一个完美的工作代码,以确切的形式:填充0时用“IllegalFormatConversionException:d!= java.lang.String”?

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

这将垫好听到00000001

现在我踢了twoKeyChar从表中得到一个字符串的缺口lastRecord从表中获取int。你可以看到这个概念本质上是相同的 - 我将一个int转换为一个字符串,并尝试用0填充它;但是,这一次我得到以下错误:

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

的代码如下:

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); 
} 

我觉得我必须输入一些错误,因为没有理由,因为它打破上次它工作的时候。任何帮助/提示表示赞赏!谢谢!

+1

以人的形式表示“格式说明符'd'不适用于字符串值”。 – 2012-06-05 19:31:32

回答

12

你不需要Integer.toString()

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

String.format()会进行转换和填充。

+0

我要去我的角落,感觉很愚蠢......很棒!谢谢!在10分钟内接受答案时,让我,嘿。 –

+2

它不是你不需要做toString,但更像你不能。字符串格式的第一个参数中的“d”需要一个十进制整数。因此错误。 –