Reputation: 293
I have this code and I'm trying to format the output as shown below, but when I start the program and reach to printf, it stops and gives error Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String
variables:
itemcode=integer
selecteditems=string
perkg=double
userkg=string
quantity-integer
dry=string
total=double
Note: those are changeable variables into for loop.
System.out.printf("%-4d %-13s %8.2f %8.2f %-8d %-10s %8.2f %n", itemcode,
selecteditems, per_kg, userkg, quantity, dry, total);
Upvotes: 1
Views: 369
Reputation: 10945
You have defined userkg
as a String, but you are trying to print it as a decimal. You need to change the type of the variable to double.
When you define a format string, you are telling java both the way you would like your variable displayed, and what type it should expect.
For instance, %8.2f
requires that you give a float or double as an argument.
If instead you pass in a variable of type String, you will get an error:
e.g.
float aFloat = 0;
String notAFloat = "";
System.out.printf("%8.2f %8.2f", aFloat, notAFloat);
...gives the following error:
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)
Upvotes: 2