Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I receiving IllegalFormatConversionException in Java for this code?

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?

like image 526
user1590710 Avatar asked Aug 13 '12 14:08

user1590710


People also ask

What is formatting in Java?

Java Formatter is a utility class that can make life simple when working with formatting stream output in Java. It is built to operate similarly to the C/C++ printf function. It is used to format and output data to a specific destination, such as a string or a file output stream.

What are format specifiers in Java?

Format specifiers begin with a percent character (%) and terminate with a “type character, ” which indicates the type of data (int, float, etc.) that will be converted the basic manner in which the data will be represented (decimal, hexadecimal, etc.)


2 Answers

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));
like image 101
davidfmatheson Avatar answered Sep 21 '22 04:09

davidfmatheson


you are formatting a floating point and not an integer. insert a %d instead of the %f and it should work

like image 24
David Biderman Avatar answered Sep 22 '22 04:09

David Biderman