[英]Java System.out.format with double array
I am trying to output information with System.out.format using a double[] array as the argument. 我试图使用double []数组作为参数使用System.out.format输出信息。 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. 据说它可以很好地使用字符串。
Java will autobox your double
to a Double
, but it won't autobox your double[]
to a Double[]
, so it doesn't match Object[]
. Java会将你的double
自动装箱到Double
,但它不会将你的double[]
装箱到Double[]
,因此它与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. 因此,您的数组不会被解压缩到Object...
varargs中,而是被视为数组本身 - 显然,它不能被格式化为double。
If you declare your array as Double[]
instead of double[]
, the call to format
works. 如果将数组声明为Double[]
而不是double[]
,则对format
的调用起作用。
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). 它不起作用,因为数组不是double(在Java中,数组是一个类,因此它就像一个通用指针)。 You need to specify exactly what will be outputted, and you did - it's the %f
format specifier . 你需要准确指定输出的内容,你做了 - 它是%f
格式说明符 。 ArraySomething[] doesn't match.. ArraySomething []不匹配..
See here for more on Java's Formatting and here - How does array class work in Java? 有关Java格式化的更多信息,请参阅此处 - 数据类如何在Java中工作? , for Java arrays. ,对于Java数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.