Why can’t printf be formatted with an array of ints?
I want to format an output string with a series of variables. When I use an array of strings, this works as expected:
String[] myArray = new String[3];
// fill array with strings
System.out.printf("1: %s \n2: %s \n3: %s\n", myArray);
I want to use this to print the results of simulated dice-throws, so I use an array of ints. However, this doesn’t work:
int[] myArray = new int[3];
// fill array with numbers
System.out.printf("开发者_Go百科1: %d \n2: %d \n3: %d\n", myArray);
Exception in thread "main" java.util.IllegalFormatConversionException: d != [I
Of course, I could use myArray[0]
etc. for every element, but this doesn’t seem very elegant.
Why is this so and how can I achieve the desired result?
printf
is a variable argument method that takes a String
(the format string) and an arbitrary number of arguments (to be formatted).
Varargs are implemented as arrays in Java. printf
expects Object
as its varargs type, therefore the internal type is Object[]
.
A String[]
is-a Object[]
(i.e. it can be cast to that type), so the elements of the String[]
will be interpreted as the separate arguments.
An int[]
however, can't be cast to an Object[]
so the int[]
itself will be the first (and only) element of the varargs array.
Then you try to format the int[]
using %d
which won't work, because an int[]
is not a (single) decimal number.
This is because String
is a reference type (i.e. subclass of Object
) while int
is a primitive type. The printf method expects an array of Object
s (actually variable length argument list), and so a String[]
fits in fine. Whenever you pass in a int[]
, since int
is not an Object
but int[]
is, it takes the whole int[]
as a single object and considers that a single argument.
I'm not sure but String is an object whereas int is not.
printf
takes an Object array for the parameters.
Try Integer[] myArray
instead.
printf uses variable arguments so that we can pass 0 t0 n arguments to it:
public PrintString printf(String format, Object... args);
out.printf("%s:%s", a, b);
That is the equivalent of:
out.printf("%s:%s", new Object[] { a, b });
So, getting back to your question, for an array, you can just write:
out.printf("%s:%s", things);
精彩评论