为什么我在这个代码中接收Java的IllegalFormatConversionException? [英] Why am I receiving IllegalFormatConversionException in Java for this code?
问题描述
我目前正在研究从网络获取数据并在JTextArea上打印出来的代码。在这之间,我试图根据小数位数来对齐数字。这是执行小数对齐之前的代码:
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?
推荐答案
BuildShort
方法返回一个整数,然后给它一个float的格式模式。只要在它前面粘贴一个 double
>,就可以了:
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));
这篇关于为什么我在这个代码中接收Java的IllegalFormatConversionException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!