String.format 不允许 int



我一直在寻找一种快速简便的方法来将 int 格式化为带有两个前导零的字符串。我找到了这个 https://stackoverflow.com/a/4377337/47690 答案,它看起来像我需要的。所以我这样实现它

int i = 34; //could be any value but you get the idea   
String.format("%03d", i);

但是,Eclipse似乎抱怨String.format需要为其第二个参数提供Object[]。这是怎么回事?

如果要打印i的值,可以使用:

System.out.printf("%03d", i);

而不是

System.out.println(String.format("%03d", i));

编辑:

我也在 Java 6 中尝试了您的代码,但它不起作用。所以,我使用了printf()。哦。不好意思!我清理了项目,它奏效了。

我正在使用Java 6和Eclipse Helios。

检查项目设置

project -> Properties -> Java Compiler -> Compiler compliance level

你可能在 Java 1.4 中无法识别 vararg

String format(String format, Object ... args)

下面的编译和运行在Java 7下运行良好(Eclipse Juno SR1对此感到满意):

public class Main {
    public static void main(String[] args) {
        int i = 42;   
        System.out.println(String.format("%03d", i));
    }
}

错误消息是一个红鲱鱼:即使最后一个参数是Object...(又名Object[]),自动装箱也会处理所有事情。

我怀疑您使用的是过时的 Java 和/或 Eclipse,或者您的 Eclipse 项目中的编译器合规性级别设置为 1.5 之前(即使您使用的是 1.5+)。

字符串 s = String.format("%04d", i);

此代码代表数字中的 4 位数字来串,因此.. 如果您使用 %04d,我将预先获得两个试用零

虽然int i是一个原始对象,它的预期对象作为它的参数,

它的JVM将在内部处理转换为对象数据类型

根据Java实现看到这个..

public static String format(String format, Object ... args) {
return new Formatter().format(format, args).toString();
}

动态附加零的示例代码...

导入java.text.DecimalFormat;公共类 ArrayTest {

public static void main(String[] args) {
    int i = 34; //could be any value but you get the idea   
    int zeroCount = 2;
    String s = String.format("%d", i);
    int length = s.length()+zeroCount;
    System.out.println(String.format("%0"+length+"d", i));
    // second way u can achieve 
    DecimalFormat decimalFormat = new DecimalFormat();
    decimalFormat.setMinimumIntegerDigits(length);
    System.err.println(decimalFormat.format(i));
}

}

来到System.format的参数,它可以接受无限的参数,因为它是一个varargs对象作为第二个参数

检查此网址http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29

相关内容

最新更新