3

I am trying to output information with System.out.format using a double[] array as the argument. This does not work:

out.format("New dimensions:\n" +
        "Length: %f\n" +
        "Width: %f\n\n",
        doubleArray);

This, however, does:

out.format("New dimensions:\n" +
        "Length: %f\n" +
        "Width: %f\n\n",
        doubleArray[0], doubleArray[1]);

Why doesn't the first format work? It supposedly works with strings just fine.

Fredrik
  • 5,759
  • 2
  • 26
  • 32
joelises
  • 85
  • 5

2 Answers2

4

Java will autobox your double to a Double, but it won't autobox your double[] to a Double[], so it doesn't match Object[]. As a result, instead of being unpacked into the Object... varargs, your array is being treated as the array itself -- which, obviously, can't be formatted as a double.

If you declare your array as Double[] instead of double[], the call to format works.

Etaoin
  • 8,444
  • 2
  • 28
  • 44
1

It doesn't work because an array isn't a double(in Java an array is a class, so it's like a general pointer here). You need to specify exactly what will be outputted, and you did - it's the %f format specifier. ArraySomething[] doesn't match..

See here for more on Java's Formatting and here - How does array class work in Java? , for Java arrays.

Community
  • 1
  • 1
Caffeinated
  • 11,982
  • 40
  • 122
  • 216
  • 2
    [link](http://docs.oracle.com/javase/tutorial/java/data/numberformat.html) "The syntax for these two java.io.PrintStream methods is the same: public PrintStream format(String format, Object... args)" The three dots operator is supposed to optionally take an array of arguments, but it's not working here. I get an conversion error. – joelises Apr 20 '12 at 05:39