Why am I receiving IllegalFormatConversionException in Java for this code?
Solution 1
You are receiving the error because your BuildShort
method returns an integer, and you're giving it a format pattern for a float. Just stick a double
cast in front of it, it should be fine:
NewString += String.format("%-8s%11.5f" + NewLine, "SID : ", (double)BuildShort(data,4));
Solution 2
you are formatting a floating point and not an integer. insert a %d instead of the %f and it should work
Solution 3
The error message for these format conversion errors are very poorly written by Oracle and I can't for the life of me figure out why they would have written it in such a way. Like already stated above, it means that you were trying to format an integer using a float format token.
Related videos on Youtube
user1590710
Updated on September 15, 2022Comments
-
user1590710 over 1 year
I am currently working on a code that takes data from the network and print it out on a JTextArea. In between, I am trying to alignment the number based on the decimal position. This is the code that works before implementing the decimal alignment:
private static final String NewLine = System.getProperty("line.separator"); String NetString = ""; byte[] data = p.getData(); NewString += "SID: " + BuildShort(data,4) + NewLine; NewString += "DID: " + BuildShort(data,6) + NewLine;
And this is the new one
NewString += String.format("%-8s%11.5f" + NewLine, "SID : ", BuildShort(data,4)); NewString += String.format("%-8s%11.5f" + NewLine, "DID : ", BuildShort(data,6));
which I received the error message
Exception in thread "Thread-2" java.util.IllegalFormatConversionException: f != java.lang.Integer at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source) at java.util.Formatter$FormatSpecifier.printFloat(Unknown Source) at java.util.Formatter$FormatSpecifier.print(Unknown Source) at java.util.Formatter.format(Unknown Source) at java.util.Formatter.format(Unknown Source) at java.lang.String.format(Unknown Source) at MT302.ParsePacket(MT302.java:97) at MK20_DataView.run(MK20_DataView.java:261) at java.lang.Thread.run(Unknown Source)
Do you know why I am receiving this error?
-
user1590710 over 11 yearsthank you, i didn't know the input value can only accept double value only
-
Charles over 11 yearsIt doesn't have to take a double, you just told it to expect one.
-
Steve Kroon about 11 yearsBut why doesn't the integer get promoted to a double automatically?