简体   繁体   English

String.format()出错

[英]Error with String.format()

Below is simple code, I got java.util.IllegalFormatConversionException whenever i == 0 . 下面是简单的代码,只要i == 0 ,我就得到了java.util.IllegalFormatConversionException

java.util.Random r = new java.util.Random();
int i = r.nextInt(2);
String s = String.format(
    String.format("%s", i == 0 ? "%d" : "%f"),
    i == 0 ? r.nextInt() : r.nextFloat());
System.out.println(s);

The stack trace: 堆栈跟踪:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Float
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4011)
    at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2725)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2677)
    at java.util.Formatter.format(Formatter.java:2449)
    at java.util.Formatter.format(Formatter.java:2383)
    at java.lang.String.format(String.java:2781)
    at hb.java.test.App.testCompiler(App.java:17)
    at hb.java.test.App.main(App.java:10)

Could someone please explain if I'm doing wrong? 有人可以解释一下我做错了吗? Thank you. 谢谢。

That is a weird one. 这是一个奇怪的。 Looks like the second conditional (i == 0 ? r.nextInt() : r.nextFloat()) is casting both to Float because of the second parameter. 看起来第二个条件(i == 0?r.nextInt():r.nextFloat())由于第二个参数而将两者都转换为Float。 Never seen this before. 从来没见过这个。

Here's something that works: 这是有效的:

    public static void main(String[] args) {
        java.util.Random r = new java.util.Random();
        int i = r.nextInt(2);
        String s;
        if(i == 0){
            s = String.format("%d", r.nextInt());
        }
        else{
            s = String.format("%f", r.nextFloat());
        }
        System.out.println(s);
    }

i == 0 ? r.nextInt() : r.nextFloat() i == 0 ? r.nextInt() : r.nextFloat() has the type float. i == 0 ? r.nextInt() : r.nextFloat()的类型为float。 ?: operator cannot return both int and float . ?:运算符不能同时返回intfloat

How about this: 这个怎么样:

final String s;
if ( i == 0 )
{
    s = String.format("%d", r.nextInt( ));
}
else
{
    s = String.format("%f", r.nextFloat( ));
}

In String.format the first parameter is the format but in your example above you have the initial %s as the first parameter then %d or %f as the object to substituted for 在String.format中,第一个参数是格式,但在上面的示例中,您将初始%s作为第一个参数,然后将%d或%f作为要替换的对象

You need to do something like this: 你需要做这样的事情:

String s = String.format(i == 0 ? "%d" : "%f", i == 0 ? r.nextInt() : r.nextFloat());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM