Young Young -4 years ago 48
Java Question

IllegalFormatConversionException

I'm doing an exercise about output formatting on Eclipse and an exception was thrown. I don' know how to fix it. I need to print out the 20 numbers from 50 to 1000, step 50, and their square roots. The integers need 4 digits max, and the float numbers need 3 digits before and after the decimal point.

//exercise
int j;
for ( j = 50; j <= 1000; j += 50){
double sqrt = Math.sqrt(j);
System.out.printf("START%4dEND", "START%6.3fEND %n", j, sqrt);
}


The exception message I got is like this:

STARTException in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at Output.main(Output.java:16)

Answer Source

In this line

System.out.printf("START%4dEND", "START%4.3fEND %n", j, sqrt);

your second argument to printf is a string, but it expects an integer. Try combining the first two arguments like so:

System.out.printf("START%4dEND START%4.3fEND %n", j, sqrt);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download