0

I want to print a sentence with formatted doubles without having to use several print statements. These are a couple of the statement I tried to run:

  System.out.printf("( %.2f", real + ", %.2f", imaginary + ")"); 

  System.out.printf("(" + "%.2f",real + ", " + "%.2f",imaginary + ")");

However, this is the error I get

java.util.IllegalFormatConversionException: f != java.lang.String
    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.io.PrintStream.format(Unknown Source)
    at java.io.PrintStream.printf(Unknown Source)
    at ComplexNumber.print(ComplexNumber.java:17)
    at ComplexClient.main(ComplexClient.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

Am I just using the printf statement incorrectly? Or is what I'm trying to do not possible? Thanks

1 Answers1

0

You don't mix in the variables within the construction of your format string. You should create your format string as the first parameter, with all variables passed in afterwards. The number of variables passed in must match the number of placeholders in the format string, and they must match the formats specified by the placeholders.

Try:

//                <- format    ->
System.out.printf("( %.2f, %.2f)", real, imaginary);
//                                 ... variables afterwards here

This matches the printf method signature, which takes in the format String first, followed by any number of Object variable parameters.

rgettman
  • 176,041
  • 30
  • 275
  • 357