Error with String.format ()

Below is a simple code, I got java.util.IllegalFormatConversionException whenever i == 0 .

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

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) 

Can someone explain if I'm not mistaken? Thanks.

+4
source share
4 answers

This is strange. It looks like the second conditional (i == 0? R.nextInt (): r.nextFloat ()) discards both Float parameters due to the second parameter. Never seen this before.

Something works here:

  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); } 
+5
source

i == 0 ? r.nextInt() : r.nextFloat() i == 0 ? r.nextInt() : r.nextFloat() is of type float. The ?: Operator cannot return either int or float .

+2
source

How about this:

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

In String.format, the first parameter is the format, but in your example above, you have the initial% s as the first parameter, and then% d or% f as the object to replace

You need to do something like this:

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

Source: https://habr.com/ru/post/1394932/


All Articles