2014-10-07 66 views
1

我有这样的代码,我想,如下所示格式化输出,但是当我启动程序,达到对printf,它停止并给出错误Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String用printf

variables:  
itemcode=integer 
selecteditems=string 
perkg=double 
userkg=string 
quantity-integer 
dry=string 
total=double 

格式化输出的java注意:这些是for循环的可变变量。

System.out.printf("%-4d %-13s %8.2f %8.2f %-8d %-10s %8.2f %n", itemcode, 
    selecteditems, per_kg, userkg, quantity, dry, total); 
+0

这将有助于了解这些变量的值和类型的 – 2014-10-07 17:07:54

+0

可能重复(http://stackoverflow.com/questions/11936327/why-am-i-receiving-illegalformatconversionexception-in-java-for-this-code) – 2014-10-07 17:10:13

+0

为什么'%n'作为最后的格式说明符? – Rustam 2014-10-07 17:11:24

回答

2

您已经定义userkg字符串,但你要打印它作为一个小数。您需要将变量的类型更改为double

当你定义一个格式字符串时,你告诉java你希望显示你的变量的方式,以及类型它应该期望的。

例如,%8.2f要求你给浮动作为参数。

相反,如果你在String类型的变量传递,你会得到一个错误:

例如

float aFloat = 0; 
String notAFloat = ""; 
System.out.printf("%8.2f %8.2f", aFloat, notAFloat); 

...提供了以下错误:[?为什么我在Java中接收IllegalFormatConversionException此代码]

Exception in thread "main" 
    java.util.IllegalFormatConversionException: f != java.lang.String 
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045) 
at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2761) 
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2708) 
at java.util.Formatter.format(Formatter.java:2488) 
at java.io.PrintStream.format(PrintStream.java:970) 
at java.io.PrintStream.printf(PrintStream.java:871) 
at Scratch.main(Scratch.java:9)