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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help! I changed the type to Double[] and it seems to work now.
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.

1 Comment

link "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.

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.