为什么我在 Java 中收到此代码的 IllegalFormatConversionException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11936327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I receiving IllegalFormatConversionException in Java for this code?
提问by user1590710
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:
我目前正在编写从网络获取数据并将其打印在 JTextArea 上的代码。在两者之间,我试图根据小数点位置对齐数字。这是在实现十进制对齐之前工作的代码:
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?
你知道为什么我会收到这个错误吗?
回答by davidfmatheson
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:
您收到错误是因为您的BuildShort
方法返回一个整数,并且您给它一个浮点数的格式模式。double
在它前面贴一个演员表,应该没问题:
NewString += String.format("%-8s%11.5f" + NewLine, "SID : ", (double)BuildShort(data,4));
回答by David Biderman
you are formatting a floating point and not an integer. insert a %d instead of the %f and it should work
您正在格式化浮点数而不是整数。插入 %d 而不是 %f ,它应该可以工作
回答by Mark Aquino
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.
这些格式转换错误的错误消息由 Oracle 编写的非常糟糕,我一生都无法弄清楚为什么他们会以这种方式编写它。如上所述,这意味着您试图使用浮点格式标记格式化整数。