【问题标题】:"IllegalFormatConversionException: d != java.lang.String" when padding number with 0s?“IllegalFormatConversionException:d!= java.lang.String”用0填充数字时?
【发布时间】:2012-06-05 19:23:17
【问题描述】:

我昨天有一个完美运行的代码,格式如下:

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

我觉得我一定是输入了错误的东西,因为自从它上次工作以来,没有理由让它崩溃。任何帮助/提示表示赞赏!谢谢!

【问题讨论】:

  • 以人类形式表示“格式说明符d 不适用于字符串值”。

标签: java regex string-formatting


【解决方案1】:

你不需要Integer.toString():

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

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

【讨论】:

  • 我要去我的角落,感觉很笨……好接球!谢谢你!让我在 10 分钟内接受答案,呵呵。
  • 并不是你不需要做toString,而是更像你不能。 String 格式的第一个参数中的“d”需要一个十进制整数。因此出现错误。
【解决方案2】:

它对我有用,这里应该是整数 12 应该是整数。

String.format("%04d", Integer.parseInt("12"));

输出 - 0012

【讨论】:

    【解决方案3】:

    聚会很晚了。

    如果即使在实施已接受的答案后,您仍然面临String.format(); 代码的问题。

    这对我不起作用:

    String.format("%08d", stringvariable);
    

    因为两个原因:

    1. 它不会像d 所期望的那样使用小数点而不是字符串。
    2. 使用%8d 而不是%08d,因为如果我使用这个%08d,格式化程序对我不起作用

    如果您将基于字符串的变量与字符串数据一起使用。使用这个。

    String.format("%8s", stringvariable);
    

    【讨论】:

      【解决方案4】:

      在 Android 中,您应该将 %1$s ... %d ... %.2f 替换为 %1$s ... %2$d ... %3$.2f

      这样可以避免java.util.IllegalFormatConversionException: d != java.lang.Stringf != java.lang.String 异常。

      【讨论】:

        猜你喜欢
        • 2018-01-14
        • 2013-07-14
        • 2013-10-07
        • 2021-07-06
        • 1970-01-01
        • 1970-01-01
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多