1

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);
8
  • It would help to know the values and types of these variables Commented Oct 7, 2014 at 17:07
  • possible duplicate of Why am I receiving IllegalFormatConversionException in Java for this code? Commented Oct 7, 2014 at 17:10
  • why %n as last format specifier? Commented Oct 7, 2014 at 17:11
  • 1
    Are you sure that per_kg, userkg total are float or double type? It seems that at leas one of them is String. Commented Oct 7, 2014 at 17:11
  • @Rustam To add line separator dependant of OS (like \r\n on windows). Commented Oct 7, 2014 at 17:12

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.